BASH:如果是,则为基本,然后进行变量分配 [英] BASH: Basic if then and variable assignment

查看:80
本文介绍了BASH:如果是,则为基本,然后进行变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯使用csh,因此使用bash有点烦人.此代码有什么问题?

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

推荐答案

按照标准,它应该是

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

在普通的shell脚本中,您使用[]来测试值.在[ ]中没有像><这样的类似算术比较运算符,只有-lt-le-gt-ge-eq-ne.

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.

在使用bash时,首选[[ ]],因为变量不受拆分和路径名扩展的限制.您也无需使用$扩展变量即可进行算术比较.

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

这篇关于BASH:如果是,则为基本,然后进行变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆