0

I am doing a simple if else program in bash.

I am trying to understand the difference between [ and (( and [[

this below code works fine

#!/bin/bash
echo "enter a number"
read num
if [ $num -ge 1 -a $num -lt 10 ]
then
echo "A"
elif [ $num -ge 10 -a $num -lt 90 ]
then
echo "B"
elif [ $num -ge 90 -a $num -lt 100 ]
then
echo "C"
else
echo "D"
fi

This code also works fine

#!/bin/bash
echo "enter a number"
read num
if (( num >= 1)) && ((num<10))
then
echo "sam"
elif ((num >= 10)) && ((num < 90 ))

then
echo "ram"
elif ((num >= 90)) && ((num  <100))
then
echo "rahim"
else
echo "tara"
fi

but when i try to use [[ there is a problem

#!/bin/bash
echo "enter a number"
read num
if [[ "num" -ge "1" ]] && [[ "num" -lt "10" ]]
then
echo "A"
elif [[ "num" -ge "10" ]] && [[ "num" -lt "90" ]]
then
echo "B"
elif [[ "num" -ge "90" ]] && [[ "num" -lt "100" ]]
then
echo "C"
else
echo "D"
fi


sourav@LAPTOP-HDM6QEG8:~$ sh ./ifelse2.sh
enter a number
50
./ifelse2.sh: 4: [[: not found
./ifelse2.sh: 7: [[: not found
./ifelse2.sh: 10: [[: not found
./ifelse2.sh: 14: echo D: not found

can someone explain this,i tried without double quoting the variable too.

  • 2
    When you run `sh scriptname`, that forces it to be run with `sh` instead of `bash`, ignoring the `#!/bin/bash` shebang. `[[` is not a feature required by the POSIX sh standard, and `sh` isn't guaranteed to offer features not present in that standard. – Charles Duffy Nov 30 '22 at 17:30
  • BTW, `(( num >= 90 ))` doesn't work reliably with `sh` either; that syntax too needs `bash` or another extended shell to have a guarantee of support. – Charles Duffy Nov 30 '22 at 17:31
  • 1
    Eh, `[[ num -ge 90 ]]` isn't that much different from `[[ $num -ge 90 ]]`, but since I wouldn't recommend using `[[ ... -ge ... ]]` in the first place (use `(( ... >= ... ))` instead), the difference probably isn't worth worrying about. – chepner Nov 30 '22 at 17:33
  • thanks everyone ,changing bash from sh solved the problem – Sourav Bhattacharya Nov 30 '22 at 17:59

0 Answers0