BASH: Basic if then and variable assignment

家住魔仙堡 提交于 2020-08-04 04:29:04

问题


I'm used to csh, so this is kinda irritating having to use bash. What is wrong with this code?

if[$time > 0300] && [$time < 0900]
then
$mod=2
else
$mod=0
fi

回答1:


By standard it should be

if [ "$time" -gt 300 ] && [ "$time" -lt 900 ]
then
   mod=2
else
   mod=0
fi

In normal shell scripts you use [ and ] to test values. There are no arithmetic-like comparison operators like > and < in [ ], only -lt, -le, -gt, -ge, -eq and -ne.

When you're in bash, [[ ]] is preferred since variables are not subject to splitting and pathname expansion. You also don't need to expand your variables with $ for arithmetic comparisons.

if [[ time -gt 300 && time -lt 900 ]]
then
   mod=2
else
   mod=0
fi

Also, using (( )) for arithmetic comparisons could be best for your preference:

if (( time > 300 && time < 900 ))
then
   mod=2
else
   mod=0
fi


来源:https://stackoverflow.com/questions/18856439/bash-basic-if-then-and-variable-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!