Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Bash if-check not working [duplicate]

Writer Andrew Mclaughlin

I want to compare strings in Bash using if statements, but it doesn't work:

#!/bin/bash
os=`lsb_release -r | sed 's/.*://'`
echo $os
if [ $os="16.04" ]
then
echo "g"
elif [ $os="14.04" ]
then
echo "b"
else
echo "c"
fi
1

1 Answer

In Bash's test (synonym for [ ... ]) builtin, and also for the usually preferable [[ ... ]] expressions, you must separate all arguments and operators with spaces.

Furthermore, you should always quote your variables. It's also recommended to use indentation to make your code better readable and to use the new-style process substitution syntax $(...) instead of `...`.

Oh, and lsb_release has a -s or --short option to omit the first column, you don't need to parse it with sed.

It could look e.g. like this:

#!/bin/bash
os=$(lsb_release -rs)
echo "$os"
if [[ "$os" = "16.04" ]] ; then echo "g"
elif [[ "$os" = "14.04" ]] ; then echo "b"
else echo "c"
fi

On the other hand, for comparing one variable against multiple values, case might be prettier:

#!/bin/bash
os=$(lsb_release -rs)
echo "$os"
case "$os" in "16.04") echo "g" ;; "14.04") echo "b" ;; *) echo "c" ;;
esac