算术扩展为脚本中执行(整数)算术运算提供了一个强大的工具。 使用反引号,双括号或let将字符串转换为数值表达式相对简单。
z=`expr $z + 3` # The 'expr' command performs the expansion. |
在算术扩展中使用反引号(反引号)已被双括号取代 --((...))并且$((...))-- 以及非常方便的let结构。
z=$(($z+3))
z=$((z+3)) # Also correct.
# Within double parentheses,
#+ parameter dereferencing
#+ is optional.
# $((EXPRESSION)) is arithmetic expansion. # Not to be confused with
#+ command substitution.
# You may also use operations within double parentheses without assignment.
n=0
echo "n = $n" # n = 0
(( n += 1 )) # Increment.
# (( $n += 1 )) is incorrect!
echo "n = $n" # n = 1
let z=z+3
let "z += 3" # Quotes permit the use of spaces in variable assignment.
# The 'let' operator actually performs arithmetic evaluation,
#+ rather than expansion. |
脚本中算术扩展的示例