bash 用于获取参数的 Shell getops
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14456749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shell getops for grabbing arguments
提问by Jimmy
I have a script which should be run as either one of these two:
我有一个脚本应该作为这两个之一运行:
script.sh -t TYPE
script.sh -t TYPE -f FILE
- If it is run without a -t flag I want it to error and exit.
- If it is run with a -t flag I want to grab the value and store it in a variable called "$TYPE" and print "JUST $TYPE"
- If it is run with a -f flag I want it grab the value and store it in a variable called "$FILE" and print "$TYPE and $FILE"
- 如果它在没有 -t 标志的情况下运行,我希望它出错并退出。
- 如果它使用 -t 标志运行,我想获取该值并将其存储在名为“$TYPE”的变量中并打印“JUST $TYPE”
- 如果它使用 -f 标志运行,我希望它获取值并将其存储在名为“$FILE”的变量中并打印“$TYPE and $FILE”
From information and tutorials on both here and the internet generally this is the closest I can get. Can anyone help me put in the second conditional into this existing code?
从这里和互联网上的信息和教程中,通常这是我能得到的最接近的。谁能帮我将第二个条件放入现有代码中?
while getopts ":t:" opt; do
case $opt in
a)
echo "JUST $OPTARG" >&2
;;
\?)
echo "Error - Invalid type argument" >&2
exit 1
;;
:)
echo "Error - No type argument" >&2
exit 1
;;
esac
done
采纳答案by Faiz
Have a look at this:
看看这个:
TYPE=""
FILE=""
while getopts "t:f:" opt; do
case $opt in
t) TYPE="$OPTARG"
;;
f) FILE="$OPTARG"
;;
esac
done
if [ -z "$TYPE" ]; then
echo "No -t. Bye."
exit 1 # error
else
if [ -n "$FILE" ]; then
echo "$TYPE and $FILE"
else
echo JUST $TYPE
fi
fi
回答by user1146332
I think you get confused how you should handle command line arguments.
我认为您对如何处理命令行参数感到困惑。
The common way is that the processing of all arguments precedes the actual job of the program/script.
常见的方法是在程序/脚本的实际工作之前处理所有参数。
Further more (related to getopts) if an option is appended by a colon, that indicates that the option is expected to have an argument.
更进一步(与 相关getopts),如果一个选项附加了一个冒号,这表明该选项应该有一个参数。
Your casestatement looks overpopulated too. You don't need to test for a colon and a question mark. The whole testing can be put after the whileloop
您的case声明看起来也过多。您不需要测试冒号和问号。整个测试可以放在while循环之后
I would do it like this
我会这样做
#!/bin/bash
unset TYPE
unset FILE
#uncomment if you want getopts to be silent
#OPTERR=0
while getopts "t:f:" opt; do
case $opt in
t)
TYPE=$OPTARG
echo "JUST $OPTARG"
;;
f)
FILE=$OPTARG
;;
esac
done
if ! test "$TYPE" ; then
echo "-t is obligatory"
exit 1
fi
if test "$TYPE" && test "$FILE" ; then
echo "$TYPE and $FILE"
fi

