In Bash you can compare the strings using the syntax:
[[ $variable == "valor" ]]
Note that here $variable
do not need to have double quotes.
Here, both [[
and ==
are characteristic of Bash (what we call Bashisms ). The standard (that is, what POSIX defines) is to use [
and =
:
[ "$variable" = "valor" ]
In which case the variable must be enclosed in quotation marks to protect us from word splitting .
Note that the syntax is of the form:
if [ condiciones ]
# ^ ^ ^
That is, the spaces around [
are necessary, because [
is a command itself. This command is called test
and therefore you can use [
and test
indistinctly, as well as search your instructions doing man test
(as indicated by Trauma in your answer):
$ v="hola"
$ if test "$v" = "hola"; then echo "si"; fi
si
$ if [ "$v" = "hola" ]; then echo "si"; fi
si
Additional explanation regarding the use of double quotes within [
and [[
.
When we use [
, the variables expand causing errors if we do not put double quotes:
$ v="hola que tal"
With [
and quotation marks, the expansion is correct:
$ if [ "$v" = "hola que tal" ]; then echo "si"; fi
si
If we remove the quotes, it gives an error:
$ if [ $v = "hola que tal" ]; then echo "si"; fi
bash: [: too many arguments
Well, it's expanding to:
$ if [ hola que tal = "hola que tal" ]; then echo "si"; fi
giving 5 arguments to test
instead of the maximum 3 accepted.
On the other hand, with the Bashismo [[
you can omit the quotes:
$ if [[ $v = "hola que tal" ]]; then echo "si"; fi
si