![](/img/trans.png)
[英]How to use mutually exclusive flags in your shell and add an optional argument flag ( stuck with getopts)
[英]How to pass in shell scripts mandatory and optional flags in command line using getopts?
我想將3個參數和getopts一起傳遞給我的shell腳本。 該腳本至少需要前2個,第三個參數是可選的。 如果未設置,則使用其默認值。 因此,以下各項將同時起作用:
sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"
我嘗試按照以下方式進行操作,但是它始終忽略我輸入的參數。
usage() {
echo "Usage: Script -a <homedir> -b <threads> -c <string>"
echo "options:"
echo "-h show brief help"
1>&2; exit 1;
}
string="bla"
while getopts h?d:t:a: args; do
case $args in
-h|\?)
usage;
exit;;
-a ) homedir=d;;
-b ) threads=${OPTARG};;
-c ) string=${OPTARG}
((string=="bla" || string=="blubb")) || usage;;
: )
echo "Missing option argument for -$OPTARG" >&2; exit 1;;
* )
echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
esac
done
在剛剛按特定順序添加參數之前,我是這個getopts的新手,我不想在這里做。 我在這里閱讀了很多問題,但是一直以來都找不到我需要的方式。
我真的會在這里向您尋求幫助。 謝謝:)
您的腳本中有幾個錯誤。 最重要的是, $args
僅包含選項的字母,沒有前划線。 同樣,您給getopts( h?d:t:a:
:)提供的選項字符串也不適合您實際處理的選項( h
, ?
, a
, b
, c
)。 這是循環的更正版本:
while getopts "h?c:b:a:" args; do
case $args in
h|\?)
usage;
exit;;
a ) homedir=d;;
b ) threads=${OPTARG};;
c ) string=${OPTARG}
echo "Entered string: $string"
[[ $string=="bla" || $string=="blubb" ]] && usage;;
: )
echo "Missing option argument for -$OPTARG" >&2; exit 1;;
* )
echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
esac
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.