#!/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?
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.
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.
== 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With