1

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

Community
  • 1
  • 1
Chaitanya
  • 15,403
  • 35
  • 96
  • 137

3 Answers3

4
  • 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
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

[[ is a bash-ism i.e. it is a bash keyword.

As you are interpreting the script as sh, which presumable is not bash and does not support [[ (dash?), hence the error.

heemayl
  • 39,294
  • 7
  • 70
  • 76
1

Note: -eq ,-ne ,-gt ,-lt are used to compare integers. For string it won't work. You need to use == , !=

  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
P....
  • 17,421
  • 2
  • 32
  • 52