We want to create a simple script with 2 commands:
Anything else has to print out an error message explaining what are the accepted commands.
We end up with the following code:
#!/bin/sh
if [ $1 = "greet-eng" ] ; then
echo "Hello!"
elif [ $1 = "greet-ita" ] ; then
echo "Ciao!"
else
echo "Supported commands are 'greet-ita' and 'greet-eng'"
fi
In production it runs fine for some time until a user tells us that he got the following error:
./script.sh: 3: [: =: unexpected operator
./script.sh: 5: [: =: unexpected operator
Supported commands are 'greet-ita' and 'greet-eng'
What happened?
The problem here is in the two if
statements: we put the quote on the wrong side! String literals don't need to be quoted in bash (unless they contain wildcards).
When the script is executed, in
if [ $1 = "greet-eng" ] ; then
the $1
is replaced with its current value. If it is empty, the statement becomes:
if [ = "greet-eng" ] ; then
resulting in a syntax error.
If we move the quotes, everything works as expected:
#!/bin/sh
if [ "$1" = greet-eng ] ; then
echo "Hello!"
elif [ "$1" = greet-ita ] ; then
echo "Ciao!"
else
echo "Supported commands are 'greet-ita' and 'greet-eng'"
fi
If you can use bash
instead of sh
, you can use the [[
operator:
#!/bin/bash
if [[ $1 = greet-eng ]] ; then
echo "Hello!"
elif [[ $1 = greet-ita ]] ; then
echo "Ciao!"
else
echo "Supported commands are 'greet-ita' and 'greet-eng'"
fi