1

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

2 Answers 2

4
#!/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
Sign up to request clarification or add additional context in comments.

1 Comment

I believe the OP wanted opr to be compared against the string "plus" not the operator "+" ;)
0
#!/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

5 Comments

It's =, not ==, and extra quotes are not needed
Yep, I wanted to use the POSIX style i.e == with [[ ... ]]. Within a [ ... ], I agree = is recommended. Using quotes avoids confusion and is a good practice especially when you have some special characters. For a string like plus it is optional.
Within [] the = is required, not merely recommended. And I agree quoting is good practice, but your comment gave the impression that the extra quotes would fix OP's problem. In general, I think it's best to add some explanation in an answer, instead of just dumping code.
Most modern bash shells allow using the == within the [] as well as [[]].
You're right, I didn't notice the question had the bash tag only. I was thinking of a "standard" shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.