【问题标题】:Why can you use -eq in Bash conditionals without adding a '$' before a variable name?为什么可以在 Bash 条件句中使用 -eq 而无需在变量名前添加“$”?
【发布时间】:2014-11-11 19:39:03
【问题描述】:

我正在运行一些 Bash 条件脚本并发现如果我运行它:

#!/bin/bash

read foo

if [[ foo -eq 1 ]]; then
  echo "A"
fi

if [[ foo -eq 2 ]]; then
  echo "B"
fi

条件句在 Bash 4.2.25 下可以正常工作,无需使用 $foo。为什么不使用 $ 引用变量就可以工作?

【问题讨论】:

  • 基本上是因为它是一个bash built-in command(与Bourne shell 或POSIX shell 相比),并且已经规定变量不需要在此前缀为$一个上下文。

标签: bash variables if-statement conditional


【解决方案1】:

从 bash Conditional Constructs 的描述来看,[[ expression ]] 对表达式进行了算术扩展。如果你然后找到Shell Arithmetic 上的部分,它会说:

在表达式中,shell 变量也可以通过名称引用而不使用参数扩展语法。

“参数扩展语法”是指在名称前加上$

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多