BASH:基本 if then 和变量赋值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18856439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:12:28  来源:igfitidea点击:

BASH: Basic if then and variable assignment

bashif-statement

提问by Corepuncher

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

我习惯使用 csh,所以不得不使用 bash 有点烦人。这段代码有什么问题?

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

回答by konsolebox

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, -eqand -ne.

在普通的 shell 脚本中,您使用[]来测试值。有没有算术样比较运营商如><[ ],只有-lt-le-gt-ge-eq-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.

当您使用 bash 时,[[ ]]是首选,因为变量不受拆分和路径名扩展的影响。您也不需要使用$算术比较来扩展变量。

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