Anderson Green
Anderson Green

Reputation: 31800

Compare a Bash string literal to a local variable

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

Upvotes: 20

Views: 24543

Answers (3)

Pablo Niklas
Pablo Niklas

Reputation: 85

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

Upvotes: 3

user80168
user80168

Reputation:

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

And second - you need to add some spaces:

if [[ $lang == Java ]]

Upvotes: 2

Barmar
Barmar

Reputation: 780663

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.

Upvotes: 31

Related Questions