Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic comparison in a shell

Tags:

shell

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
like image 914
PeterMmm Avatar asked Dec 29 '25 02:12

PeterMmm


1 Answers

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.

like image 133
Jonathan Avatar answered Jan 01 '26 00:01

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!