我习惯了 csh,所以不得不使用 bash 有点烦人。这段代码有什么问题?
if[$time > 0300] && [$time < 0900]
then
$mod=2
else
$mod=0
fi
最佳答案
按照标准应该是
if [ "$time" -gt 300 ] && [ "$time" -lt 900 ]
then
mod=2
else
mod=0
fi
在普通的 shell 脚本中,您使用 [
和 ]
测试值。没有类似算术的比较运算符,如 >
和 <
在 [ ]
, 只有 -lt
, -le
, -gt
, -ge
, -eq
和 -ne
.
当你在 bash 中时,[[ ]]
首选,因为变量不受拆分和路径名扩展的影响。您也不需要使用 $
扩展变量用于算术比较。
if [[ time -gt 300 && time -lt 900 ]]
then
mod=2
else
mod=0
fi
另外,使用 (( ))
对于算术比较可能最适合您的偏好:
if (( time > 300 && time < 900 ))
then
mod=2
else
mod=0
fi
关于BASH:基本 if then 和变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18856439/