I have following bash script:

echo "Enter your name: "
read name

if [ ${name}=="sam" ]  
        echo "Hi Sam!"
        echo "Who the hell are you?"

I want it to display "Who the hell are you?" if the entered name is not "sam". But it displays "Hi Sam!" even when I enter random string.

What is the problem here?


Please read bash tutorials and manual on using conditional expressions, e.g. [ ] and test.

In short:

  1. There's no need to use ==, as = is enough.
  2. You must put spaces before and after = because otherwise instead of comparing you're assigning the right part of the expression to the left one.
  3. Do quote your variables

The net result:

if [ "${name}" = "sam" ]
  • It's probably worth mentioning that it is incorrect to use == with [, it will work in some shells but == is a bashism and should be used only with [[ tests. Additionally there is no need to use ${name}, $name will suffice.
    – jesse_b
    Sep 17 '20 at 15:48
  • 1
    No, if [ "${name}"=="sam" ]; then ... doesn't assign anything to anything. It just succeeds and takes the then branch, no matter what value $name has.
    – user414777
    Sep 17 '20 at 16:06
  • Actually it does: a=="1";echo $a => =1 Sep 17 '20 at 17:03
  • Not in [ a=="1" ]
    – user414777
    Sep 17 '20 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.