简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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