我正在测试我的脚本的第一个参数是否是 --foo
if [ $# > 1 ]
then
if [[ "$1" = "--foo" ]]
then
echo "foo is set"
foo = 1
fi
fi
if [[ -n "$foo"]]
then
#dosomething
fi
如果 --foo
作为参数之一出现,而不一定是第一个参数,有人能告诉我测试 bash 的方法是什么吗?
最佳答案
如果您想支持长选项,您应该使用外部 getopt
实用程序。如果您只需要支持短选项,最好使用 Bash 内置的 getopts
。
下面是一个使用getopts
的例子(getopt
差别不大):
options=':q:nd:h'
while getopts $options option
do
case $option in
q ) queue=$OPTARG;;
n ) execute=$FALSE; ret=$DRYRUN;; # do dry run
d ) setdate=$OPTARG; echo "Not yet implemented.";;
h ) error $EXIT $DRYRUN;;
\? ) if (( (err & ERROPTS) != ERROPTS ))
then
error $NOEXIT $ERROPTS "Unknown option."
fi;;
* ) error $NOEXIT $ERROARG "Missing option argument.";;
esac
done
shift $(($OPTIND - 1))
并不是说您的第一个测试将始终显示 true
结果,并且会在当前目录中创建一个名为“1”的文件。您应该使用(按优先顺序):
if (( $# > 1 ))
或
if [[ $# -gt 1 ]]
或
if [ $# -gt 1 ]
此外,对于赋值,等号两边不能有空格:
foo=1
关于bash - 在 bash 中测试命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5302440/