简体   繁体   English

如何比较BASH脚本中的字符串?

[英]How to compare Strings in BASH scripting?

I just want to know how to read a String and then compare it. 我只是想知道如何读取字符串然后比较它。 If it is "Plus", then carry on 如果是“加号”,则继续

#!/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
#!/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

If you're using bash then I strongly recommend using double brackets. 如果您正在使用bash,那么我强烈建议您使用双括号。 They're a lot better than single brackets; 它们比单支架好很多; for example, they handle unquoted variables a lot more sanely, and you can use && inside the brackets. 例如,他们更加理智地处理不带引号的变量,你可以在括号内使用&&

If you use single brackets then you should write this: 如果你使用单括号,那么你应该这样写:

if [ "$num" -eq 4 ] && [ "$opr" = 'plus' ]; then
    echo 'this is the right'
fi
#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM