20
#!/bin/bash
function getComment(){
    local lang=$1;
    local theComment=$2;
    if [$lang == "Java"] #Surprisingly, an error occurs here: prog.sh: line 6: [Java: command not found
    then
        echo "//"$theComment; return;
    else
        echo "Language not found!"; return;
    fi
}

getComment "Java" "Whoo!";

exit $?

I'm writing a Bash script that compares a variable to a string literal, and I'm using [$lang == "Java"] (as shown above) to compare the value of lang to "Java". However, this comparison produces the following error:

stderr:
prog.sh: line 6: [Java: command not found

I've tried using [$lang -eq "Java"] and ($lang -eq "Java") as well, but those statements didn't work either, and they produced exactly the same error.

Why is this error occurring, and what is the correct way to compare a local variable to a string literal?

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • 1
    This isn't relevant to your question, but you don't need semicolons at the end of lines in shell. They're only needed if you put more than one command on a single line. – Gordon Davisson Jun 17 '13 at 23:51
  • possible duplicate of [bash, command not found](http://stackoverflow.com/questions/16694586/bash-command-not-found) – chepner Jun 18 '13 at 12:55
  • 1
    Not the best duplicate, but there are many questions on Stack Overflow with the same answer: put spaces around the `[` and `]` of a `test` command. – chepner Jun 18 '13 at 12:55

3 Answers3

31

You need spaces around [ and ]:

    if [ "$lang" = "Java" ]

[ is a command (it's a synonym for test), and like any other command you delimit the parameters with spaces.

You should also put variables in double quotes, in case the value is empty or contains whitespace or wildcard characters.

Finally, the operator to perform string comparison is =, although some versions of test allow == as an extension.

Barmar
  • 741,623
  • 53
  • 500
  • 612
3

First, you have to enclose the variable between double quotes, because the variable could have some spaces or special characters.

Finally remember that "[" it's an executable by itself (usually is in /bin).

if [ "$lang" == "Java" ]; then
2

First thing is, don't use [ ] - it's better to use [[.

And second - you need to add some spaces:

if [[ $lang == Java ]]
  • The == comparison operator behaves differently within a double-brackets test than within single brackets. http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS – Oliver Atkinson Jun 17 '13 at 21:31