Chaitanya Chaitanya - 5 months ago 42
Bash Question

Unable to compare properly with if condition

I have written very simple logic below, but it is always complaining with my if condition.

Here is my code:

#!/bin/sh

UBUNTU_VERSION=`lsb_release -r | awk '{ print $2}'`
echo "UBUNTU_VERSION - $UBUNTU_VERSION"

if [[ "$UBUNTU_VERSION" -eq "14.04" ]];
then
echo "Ubuntu 14.04"
else
echo "Not Ubuntu 14.04"
fi


I get the error as :

./test.sh: 6: ./1.sh: [[: not found


If I change my code to:

if [ "$UBUNTU_VERSION" -eq "14.04" ];


or

if [ $UBUNTU_VERSION -eq "14.04" ];


I get error as :

./test.sh: 6: [: Illegal number: 14.04


I have already referred to this link to correct my code, but I am not able to fix this:

bash : Illegal number

Answer
  • Use #!/bin/bash shebang at top for using bash syntax
  • eq is for integer comparison only, use = or ==
  • Use $(...) for command substitution instead of old fashioned and buggy reverse ticks

Modified Code:

#!/bin/bash

UBUNTU_VERSION=$(lsb_release -r |  awk '{ print $2}')
echo "UBUNTU_VERSION - $UBUNTU_VERSION"

if [[ $UBUNTU_VERSION == "14.04" ]];
then
        echo "Ubuntu 14.04"
else
        echo "Not Ubuntu 14.04"
fi
Comments