Binary Operator Expected error in Shell Script
I am comparing numbers in a file by shell script. Following anippet of my code gave me line 22: [: –lt: binary operator expected Error.
Code:
max=`head -1 $1` Anyone, please debug it, as it has already costed me 4 hrs. I have found some similar threads but didn't get any satisfactory answers. Waiting for reply.... Thank you. |
Try putting this debug line immediately before the if test
Code:
echo "DEBUG: \$max is '$max', \$num is '$num'" |
@catkin
I did as you said. Both $ max and $ num showed expected values & here is the output:- Code:
DEBUG: $max is '2', $num is '2' |
Hey,
replacing -lt with -ge didn't gave any error ?. It's strange . By the way, it doesn't serve my logic. So when I changed -ge back to -lt, everything now runs fine. It's not the first time it's happening. Why is that so, gives errors and runs smoothly without any change. tale a look on my now working code, and see if there is any difference. Code:
max=`head -1 $1` Thanks for your quick reply. can you or anybody please explain this uncertain behaviour of test command ? it always consumes my lot of time. any help is much appreciated. |
Quotes are missing. -lt expects binary values instead of strings. So quote both:[ "$max" -lt "$num" ] or use double brackets if this for bash:
[[ $max -lt $num ]] |
or use arithmetic expansion so you can use the right symbol for the operator (( $max < $num ))
|
Quote:
|
Quote:
[[ <test expression> ]] is always preferred over [ <test expression> ] for reasons explained here. |
I guess I didn't read close enough, I just saw this:
for file_name and thought we were dealing with strings. And anyway they are strings unless he declares them as otherwise. I agree that using double brackets is the best way to deal with it if it's bash as it will always do what you expect. Single brackets and simple test statements are harder to get right... |
Thank You all guys. It is your great efforts that now I am able to remove the test command errors from my shell scripts.
@catkin Link given by you is really great |
All times are GMT -5. The time now is 12:14 AM. |