Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less than operator '<' in if statement results in 'No such file or directory'

Sure this is a simple one - still learning my way around sh scripts. I've got:-

if [ $3 < 480 ]; then
  blah blah command
else
   blah blah command2
fi

$3 is a passed variable, again an integer. However, when this script is run, it reports:-

line 20: 480: No such file or directory

Confused.

like image 898
waxical Avatar asked Dec 13 '22 10:12

waxical


2 Answers

Please use [ "$3" -lt 480 ] or it will be treated as input redirection inside the brackets. That's why you got the error: 480: No such file or directory.

To review the available alternatives:

  • [ "$3" -lt 480 ] -- numeric comparison, compatible with all POSIX shells
  • [ "$3" \< 480 ] -- string comparison (generally wrong for numbers!), compatible with all POSIX shells
  • [[ $3 < 480 ]] -- string comparison (generally wrong for numbers!), bash and ksh only
  • (( $3 < 480 )) -- numeric comparison, bash and ksh only
  • (( var < 480 )) -- numeric comparison, bash and ksh only, where $var is a variable containing a number

check http://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions to know more information.

like image 86
Mu Qiao Avatar answered May 18 '23 22:05

Mu Qiao


I think you should use:

if [ $3 -lt 480 ]; then
 blah blah command
else
 blah blah command2
fi
like image 27
Zitrax Avatar answered May 18 '23 20:05

Zitrax