Less than operator '<' in if statement

2019-01-20 12:17发布

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.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-20 12:35

probably in condition you need to use:

if [[ $3 -lt 480 ]]
查看更多
Fickle 薄情
3楼-- · 2019-01-20 12:45

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.

查看更多
甜甜的少女心
4楼-- · 2019-01-20 12:46

I think you should use:

if [ $3 -lt 480 ]; then
 blah blah command
else
 blah blah command2
fi
查看更多
登录 后发表回答