1

I'm trying to compare strings. I get "command not found" error. How do I compare the strings?

Code:

 #!/bin/bash 
 STR="Hello World" 
 if [$STR="Hello World"]; then
   echo "passed test"
 else
   echo "didn't pass test"
 fi 

Output:

 test.sh: line 4: [Hello: command not found
 didn't pass test

1 Answer 1

4

You should add spaces. Treat [[ or [ as if it's another command like test and other builtins. And like other commands, it requires a space after its name. It's also recommended that you use [[ ]] over [ ] in Bash since [[ ]] doesn't split its variables with IFS and do pathname expansions. It also has more features over the other.

#!/bin/bash
STR="Hello World"
if [[ $STR = "Hello World" ]]; then
    echo "passed test"
else
    echo "didn't pass test"
fi
Sign up to request clarification or add additional context in comments.

Comments

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.