请教一个 shell 语法的问题

#! /bin/sh

COUNTER=1
while [ "$COUNTER" -lt 10 ]; do
  echo "Here we go again"
  COUNTER=$(($COUNTER+1))
done

请问 $COUNTER+1 外面套两个 (),最后还加上一个 $

我理解是套一个就可以返回数值了,然后用$把值变为变量。但是执行时报错.

clipboard.png

请教诸位,这个是怎么回事?

阅读 2.1k
2 个回答

根据 bash 手册:

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is:

         $((expression))

所以, 当你要获取 arithmetic evaluation 的值的时候, 要加 $. 不获取它的值时, 不用加$.
Arithmetic ExpansionArithmetic Evaluation是不同的.

ARITHMETIC EVALUATION

The shell allows arithmetic expressions to be evaluated, under certain circumstances.

Arithmetic Evaluation 可以作为单独的命令使用, 而 Arithmetic Expansion 是获取 arithmetic evaluation 命令的结果. 如:

(( 2 > 3 )) # valid
$((2 > 3))  # 0: command not found
(( 2 > 3 )) || echo yes  # yes

语法就按规定的来吧。
其它方式:

((COUNTER++))
let COUNTER++
COUNTER=$[COUNTER+1]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题