Ghassar Qhasar
Ghassar Qhasar

Reputation: 75

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

Upvotes: 1

Views: 295

Answers (2)

Tuxdude
Tuxdude

Reputation: 49593

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

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 362157

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

Upvotes: 4

Related Questions