我正在测试我的脚本的第一个参数是否为--foo
if [ $# > 1 ]
then
if [[ "$1" = "--foo" ]]
then
echo "foo is set"
foo = 1
fi
fi
if [[ -n "$foo"]]
then
#dosomething
fi
请问有没有用bash的方法来测试参数列表中是否包含--foo
,不一定在第一个位置?
我正在测试我的脚本的第一个参数是否为--foo
if [ $# > 1 ]
then
if [[ "$1" = "--foo" ]]
then
echo "foo is set"
foo = 1
fi
fi
if [[ -n "$foo"]]
then
#dosomething
fi
请问有没有用bash的方法来测试参数列表中是否包含--foo
,不一定在第一个位置?
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
正如Dennis所指出的那样,getopt
和getopts
是解析命令行参数的标准方式。如果想要另一种替代方式,可以使用特殊变量$@,它会扩展成所有的命令行参数。因此,你可以在测试中使用通配符来测试它:
#!/usr/bin/env bash
if [[ $@ == *foo* ]]
then
echo "You found foo"
fi
话虽如此,但你最好尽早学会getopt。
shopt -s globstar
、zsh和ksh93进行递归式全局匹配。 - Dennis Williamson