bash 表达式类型

bash 表达式类型

bash 表达式类型有什么区别?我试图回答有关如何在 bash 中增加变量的问题,但似乎有些方法大致相同。我想知道它们中的大多数是否只是向后兼容?

这是我找到的所有可以增加变量的方法。它适用于所有后面的 bash 表达式类型,方法是用其中一个表达式替换表达式(最后一个除外)。

var=var+1
var=$((var+1))
var=$((var))+1
var=${var}+1
var=$var+1
var+=1
++var
var++
  • let表达
  • ((表达))
  • $((表达))
  • `表达`

接缝启动一个新的 bash 环境,继承当前环境,但不影响它,并且它不支持++varvar++。仅当像这样调用时:`((表达式)); echo $var`

因此,基本上,$((表达式))似乎可以完成其他所有函数能完成的任务,但最后一个函数(`表达式`)却会影响局部环境。

答案1

((expression))
              The  expression  is  evaluated  according to the rules described
              below under ARITHMETIC EVALUATION.  If the value of the  expres‐
              sion  is  non-zero, the return status is 0; otherwise the return
              status is 1.  This is exactly equivalent to let "expression".

       [[ expression ]]
              Return a status of 0 or 1 depending on  the  evaluation  of  the
              conditional  expression expression.  Expressions are composed of
              the primaries described  below  under  CONDITIONAL  EXPRESSIONS.
              Word  splitting  and pathname expansion are not performed on the
              words between the [[ and  ]];  tilde  expansion,  parameter  and
              variable  expansion, arithmetic expansion, command substitution,
              process substitution, and quote removal are  performed.   Condi‐
              tional operators such as -f must be unquoted to be recognized as
              primaries.

这涵盖了有关 bash 表达式类型的基础知识,来自 bash 手册页。有关算术表达式的更多信息,请参阅这。

资料来源:

man bash

http://www.softpanorama.org/Scripting/Shellorama/arithmetic_expressions.shtml

相关内容