Arithmetic comparison in a shell

2019-05-18 04:42发布

问题:

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

回答1:

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.



回答2:

Replace < with -lt

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



回答3:

"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



回答4:

#!/bin/sh
let a=30
let b=100
let x=$a-$b
echo $a $b $x
if(($a < $b)) then 
  echo ok
fi


标签: shell