Fadi Fadi - 1 year ago 127
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"


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

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


Answer Source

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

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

The second one is just unnecessarily verbose.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download