【问题标题】:My bash script doesn't print the flags我的 bash 脚本不打印标志
【发布时间】:2016-05-20 07:45:04
【问题描述】:

我不确定我的 bash 脚本有什么问题,因为它没有打印给定的标志,也没有在 case 语句中回显它们:

 26 while getopts ":a:b:p:u" opts;
 27 do
 28   case $opts in
 29     a) echo got an A flag;;
 30     b) echo got an B flag;;
 31     u) user=$OPTARGS echo $user;;
 32     p) pass=$OPTARGS echo $pass;;
 33     ?) echo I don\'t know what flag is this;;
 34 esac
 35 done
 36 
 37 echo user: $user pass: $pass

我是这样称呼它的:

bash-4.3$ ./functionexample.sh -p 123 -u mona

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    这应该可行:

    while getopts ":a:b:p:u" opts
    do
       case $opts in #removed the dot at the end
        a) echo "got an A flag";;
        b) echo "got an B flag";;
        u) user="$OPTARGS"
           echo "$user"
           #double quote the variables to prevent globbing and word splitting
        ;;
        p) pass="$OPTARGS"
        #Passwords can contain whitespace in the beginning.
        #If you don't double quote , you loose them while storing.
        #eg. pass=$@ will strip the leading whitespaces in the normal case.
           echo "$pass"
        ;;
        ?) echo "I don't know what flag is this" 
        #Better double quote to make echo easy, consider something like \\\\\\
        #count the hashes? eh?
        ;;
       esac
    done
    

    【讨论】:

    • 在分配变量时不需要引用!
    • echo 中的 bash 根本不是 -e。那个缩进是错误的,你删除的点是什么?没有 : 在 "u" 之后就不行了 加油!
    • 一旦缩进正确,答案有效并且愚蠢的 cmets 被删除,我将删除我的反对票和 cmets。
    • @Camusensei 将一个变量分配给另一个变量时可能不需要引用,但这也没有什么坏处。 sjsam 写的是在将变量传递给命令时分词,在这种情况下引用很重要。
    【解决方案2】:

    在 IRC bash 频道的帮助下,我得到了修复:

    26 while getopts ":a:b:p:u:" opts;
     27 do
     28   case $opts in
     29     a) echo got an A flag;;
     30     b) echo got an B flag;;
     31     u) user=$OPTARG; echo $user;;
     32     p) pass=$OPTARG; echo $pass;;
     33     ?) echo I don\'t know what flag is this;;
     34 esac
     35 done
     36 
     37 echo user: $user pass: $pass
    

    【讨论】:

    • 我同意变量不需要引用。但是使用 echo ,建议您将其双引号以防止出现不良行为。考虑variable="string spanning two lines"echo $variable 可能不会产生您希望的结果,但echo "$variable" 会:-) 一旦您进行更正,我将删除反对票。
    • 我并不是在质疑您在 bash 中的权威,因为我确信您知道自己在做什么。我指出的测试用例在问题的前提下是完全合理的,我相信这对未来的读者会很有用。在这里投反对票没什么大不了的,我已经撤回了。 ;)
    猜你喜欢
    • 2012-12-15
    • 2022-01-04
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多