您可能需要修改您的要求一點點,使用腳本,如:
members.sh --name [名] --age [年齡] --sex [M/F] --add [地址] --city [城市] --mobile [手機號碼] --email [電子郵件ID]
如果這是你OK ......你可能會考慮寫這樣的:
#!/bin/sh
while getopts ":-:" arg
do
case "${arg}" in
-)
case "${OPTARG}" in
sex)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
sex=${val};
;;
age)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
age=${val};
;;
name)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
name=${val};
;;
add)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
add=${val};
;;
city)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
city=${val};
;;
mobile)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
mobile=${val};
;;
email)
val="${!OPTIND}"; OPTIND=$(($OPTIND + 1))
echo "Parsing option: '--${OPTARG}', value: '${val}'" >&2;
email=${val};
;;
esac;;
esac
done
err=0;
if [ -z "${sex+xxx}" ]; then echo sex is not set at all; err=1;fi
if [ -z "${name+xxx}" ]; then echo name is not set at all;err=1; fi
if [ -z "${age+xxx}" ]; then echo age is not set at all; err=1; fi
if [ -z "${city+xxx}" ]; then echo city is not set at all; err=1; fi
if [ -z "${add+xxx}" ]; then echo add is not set at all; err=1; fi
if [[ $err -eq 1 ]]
then
echo "incorrect usage"
exit 1
else
echo "All mandatory fields are set"
fi
PS :我沒有涵蓋所有必填字段..根據我的解決方案,將5個參數[名稱,年齡,性別,城市和添加]作爲必填項。whil電話和電子郵件是可選的參數..
該代碼只需要輸入並將它們存儲在一個變量..請編寫自己的代碼進一步驗證。
輸出示例:
$ sh n.sh --name nishant --age 24 --sex M --add "New Delhi India" --city Noida
Parsing option: '--name', value: 'nishant'
Parsing option: '--age', value: '24'
Parsing option: '--sex', value: 'M'
Parsing option: '--add', value: 'New Delhi India'
Parsing option: '--city', value: 'Noida'
All mandatory fields are set
你試過getopts的? –
是的,但它不起作用 – user3365592