【问题标题】:How to compare Strings in BASH scripting?如何比较 BASH 脚本中的字符串?
【发布时间】:2013-02-21 19:08:56
【问题描述】:

我只想知道如何读取一个字符串然后比较它。如果是“加号”,则继续

#!/bin/bash 

echo -n Enter the First Number:
read num
echo -n Please type plus:
 read opr


if [ $num -eq 4 && "$opr"= plus ]; then

echo this is the right


fi

【问题讨论】:

    标签: string bash command-line terminal


    【解决方案1】:
    #!/bin/bash 
    
    echo -n Enter the First Number:
    read num
    echo -n Please type plus:
     read opr
    
    
    if [[ $num -eq 4 -a "$opr" == "plus" ]]; then
    #               ^            ^    ^
    # Implies logical AND        Use quotes for string
        echo this is the right
    fi
    

    【讨论】:

    • =,不是==,不需要额外的引号
    • 是的,我想使用 POSIX 样式,即 ==[[ ... ]]。在[ ... ] 内,我同意推荐=。使用引号可以避免混淆,是一种很好的做法,尤其是当您有一些特殊字符时。对于像 plus 这样的字符串,它是可选的。
    • []= 是必需的,而不仅仅是推荐。我同意引用是一种很好的做法,但你的评论给人的印象是额外的引用会解决 OP 的问题。一般来说,我认为最好在答案中添加一些解释,而不是仅仅转储代码。
    • 大多数现代 bash shell 允许在 [][[]] 中使用 ==
    • 你说得对,我没有注意到这个问题只有bash 标签。我在考虑一个“标准”外壳。
    【解决方案2】:
    #!/bin/bash 
    
    read -p 'Enter the First Number: ' num
    read -p 'Please type plus: ' opr
    
    if [[ $num -eq 4 && $opr == 'plus' ]]; then
        echo 'this is the right'
    fi
    

    如果您使用的是 bash,那么我强烈建议您使用双括号。它们比单括号好得多;例如,它们处理未加引号的变量更加明智,您可以在括号内使用&&

    如果你使用单括号,那么你应该这样写:

    if [ "$num" -eq 4 ] && [ "$opr" = 'plus' ]; then
        echo 'this is the right'
    fi
    

    【讨论】:

    • 我相信 OP 希望将 opr 与字符串“plus”而不是运算符“+”进行比较;)
    • 谢谢,这真的很有帮助
    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2021-03-08
    • 2011-01-15
    • 2015-08-30
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多