3

i want to compare two number values in a shell script (sh) but it doesn`t work:

#!/bin/sh
let a=30
let b=100
let x=$a-$b
echo $a $b $x
[ $a < $b ] && { echo ok; }

That outputs:

30 100 -70
./x: line 6: 100: No such file or directory
PeterMmm
  • 24,152
  • 13
  • 73
  • 111

4 Answers4

5

I believe that should be -lt (which stands for less than) rather than "<". "<" is for string comparisons.

Edit: Actually looking at this now it seems clear what the problem is. The "<" character does file redirection so that's what the shell is trying to do. You can escape that character by doing \< instead but as originally stated that will do string comparison rather than numeric comparison.

Jonathan
  • 1,735
  • 11
  • 17
0

Replace < with -lt

Also, lose the "let." This isn't Basic. Bill Gates and Steve Ballmer (Developers!) have nothing to do with this universe.

xcramps
  • 1,203
  • 1
  • 9
  • 9
0

"let" is perfectly fine in shell, and has nothing to do with M$ basic or what.! @OP , you can use bc to compare numbers, especially if you are also comparing floats. See here for similar example

Community
  • 1
  • 1
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
-1
#!/bin/sh
let a=30
let b=100
let x=$a-$b
echo $a $b $x
if(($a < $b)) then 
  echo ok
fi
rashedcs
  • 3,588
  • 2
  • 39
  • 40