These two codes work:
if [ $animal = "perro" ]; then
echo "El animal es un perro"
else
echo "Se desconoce el animal"
fi
Y:
if [ $animal == "perro" ]; then
...
In one I used =
and in the other ==
to do a comparison in a Bash script.
Which one should you use? The normal equal ' = ' or the double equal ' == ' ?
If you're using Bash, both are valid: POSIX has it defined
=
as the standard. Bash follows this standard, but also incorporates==
.So if you want to use the most versatile code possible, use
=
. If instead you know that it will only run in Bash, you can use==
.Emphasizing @fedorqui's answer about == : It's a bashism .
That is to say, it is a slang that is very typical of bash and of another shell that wants to adopt it; but there is no consensus . It is not in the POSIX standard .
Which says that it may not be compatible between shells that follow the POSIX standard .
Complementing the answer of @fedorqui I put an example.
Let's use
bash
,zsh
, ortcsh
:Everything looks good.
Now let's use another shell like
dash
:This happens because even though bash supports the == token , it doesn't
dash
(which is usually the default alias ofsh
!).And this does not stop. Let's continue with the exotic shell
fish
:And we have an error.
Although it is very exotic anyway
fish
, ie, little POSIX.Lastly, let's try
ash
:As we could see, we use 3 shells where the == token is not recognized.