1

I am getting this error while comparing shell argument to a string. If the code look like this:

online=true
if [ "$2" -eq '-o' ]
then
    online=false
fi
echo $online

Then for e.g. input I am getting those results:

$ ./currency.sh 2 -o
./currency.sh: line 13: [: -o: integer expression expected
true
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
siery
  • 209

1 Answers1

4

In this line:

if [ "$2" -eq '-o' ]

You have used arithmetic operator -eq which takes the second argument as a number.

Naturally, it fails for that reason alone.


When comparing strings, you can use POSIX = operator:

if [ "$2" = '-o' ]

Note, that this version should work in all shells, as it is defined by POSIX (Portable Operating System Interface).

If you want Bash-specific version:

if [[ "$2" == '-o' ]]

Note, that this version will work in only Bash (Bourne-again shell) and alike.


In contrast, double brackets [[ .. ]] and == operator are both defined in Bash only and will not work in other shells.

  • Thank you! Cold you explain in detail, why do you use double '[' around statement? I have tried both singular and double version of this and both works. – siery Mar 21 '18 at 12:24