Problem with the logical operator in the bash script

advertisements

I read in tldp.com that

if [ $condition1 ] && [ $condition2 ]

Same as: if [ $condition1 -a $condition2 ]

Returns true if both condition1 and condition2 hold true..."

but when I tried

if [ $a == 2 ] || [ $b == 4 ]
then
echo "a or b is correct"
else
echo "a and b are not correct"
fi

it gives error. I'm using bash.


Your logic is ok but your comparison operators are incorrect, you should use the '-eq' for comparing integers and '==' for strings. See 'man test' for quick reference, though it's also documented in 'man bash'.

When using integer comparison it is always best to initialise variables to 0 as well otherwise if they remain unset you will get errors.

As mentioned by c00k, use [[ rather than [ if using bash as it is a builtin so bash will not need to shell out to use the /usr/bin/[ command.

i.e.

a=0;b=0
# do something else with a or b
if [[ $a -eq 2 ]] || [[ $b -eq 4 ]]
then
    echo "a or b is correct"
else
    echo "a and b are not correct"
fi