Fadi Fadi - 3 months ago 12
Bash Question

Difference between if with or statement and elif in BASH

I'm just curious about the difference between the following:

if [[ "${foo}" == 'bar' || "${foo}" == 'bar1' ]]; then
echo "Action"
fi


and:

if [ "${foo}" == 'bar' ]; then
echo "Action"
elif [ "${foo}" == 'bar1' ]; then
echo "Same action as above"
fi


Are there any differences? Speed? Preferability for code readability? ..etc?

Thanks

Answer

A more direct (and still POSIX-compliant) version of your first statement is

if [ "${foo}" = 'bar' ] || [ "${foo}" = 'bar1' ]; then
    echo "Action"
fi

The second one is just unnecessarily verbose.

There is virtually no difference between the two in bash, as [ is a built-in command.