2011-03-14 32 views
21

我测试,看看如果第一个给我的脚本是--foo测试在bash

if [ $# > 1 ] 
then 
    if [[ "$1" = "--foo" ]] 
    then 
     echo "foo is set" 
     foo = 1 
    fi 
fi 

if [[ -n "$foo"]] 
then 
    #dosomething 
fi 

有人能pleaset告诉我什么是测试的bash的方式,如果--foo存在作为一个命令行参数争论,不一定是第一个?

+1

@Prospero:断开链接 – realtebo 2018-01-28 08:56:37

回答

33

如果您想支持长期选项,您应该使用外部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 
+0

谢谢,我转而使用getopts。我发现我无法通过随机搜索搜索bash,很多陷阱,必须更系统化:) – 2011-03-14 18:49:48

+0

@MK:有很多关于Bash的好问题和答案,还有几个包括指向好地方的指南了解更多。 – 2011-03-14 19:18:14

9

正如丹尼斯指出的,getoptgetopts是解析命令行参数的标准方法。对于另一种方法,可以使用$ @特殊变量,该特殊变量扩展为命令行参数的全部。所以,你可以测试使用通配符测试它:

#!/usr/bin/env bash 

if [[ [email protected] == **foo** ]] 
then 
    echo "You found foo" 
fi 

这就是说,如果你计算出的getopt宜早不宜迟,你会好起来的。

+4

有没有必要加倍星号。这项技术可以用作快速测试,但容易出现误报。 – 2011-03-14 19:17:16

+1

正确 - 绝对容易出现误报。我永远不会记得双星号的使用位置;我的记忆在这里失败了。感谢您的更正! – 2011-03-15 01:37:36

+1

关于双星号的唯一想法是使用'shopt -s globstar',zsh和ksh93进行递归通配的Bash 4。 – 2011-03-15 01:43:21