【问题标题】:BASH: Basic if then and variable assignmentBASH:基本 if then 和变量赋值
【发布时间】:2013-09-17 17:42:22
【问题描述】:

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

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

【问题讨论】:

  • 这也是无效的csh

标签: bash if-statement


【解决方案1】:

按照标准应该是

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

在普通的 shell 脚本中,您使用 [] 来测试值。在[ ] 中没有&gt;&lt; 等类似算术的比较运算符,只有-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 非常敏感。我输入了你所拥有的,并得到了像 ./read.sh: line 14: =0: command not found 但是当我直接复制并粘贴你的代码时,它起作用了。您是否必须始终在 "mod=2" 之前缩进 3 个空格?
  • @Corepuncher 没必要。缩进样式是任何人在 shell 脚本中的选择。我认为您在为其赋值时尝试将$ 添加到mod$mod=0。在 bash 中,它会被解释为 $mod 的扩展,它是一个空字符串加上 =0
  • Bash 需要对空格敏感,因为像 FOO= bar 这样的东西被解释为在 FOO 设置为空字符串的环境中运行命令 bar
猜你喜欢
  • 2010-12-29
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 2015-07-22
  • 2017-02-25
  • 2017-08-13
  • 2012-04-13
相关资源
最近更新 更多