Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a Bash string literal to a local variable

Tags:

bash

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

like image 984
Anderson Green Avatar asked Jun 17 '13 21:06

Anderson Green


People also ask

How do you check if a variable is equal to a string in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!= ” is used to check inequality of the strings. You can partially compare the values of two strings also in bash.

How do I compare two string variables in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What is == in bash script?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

How do you compare string literals?

To compare string literals, still use the equality and relational operators, but for objects of the string class, and not for const char*s. Using the operators for const char*s compares the pointers, and not the string literals.


1 Answers

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.

like image 65
Barmar Avatar answered Oct 14 '22 01:10

Barmar