3

我在 BASH 工作,我现在有一个白痴时刻。我有一个正在处理的项目,我将需要使用一些非常基本的算术表达式,我刚刚意识到我的很多问题是因为我的变量没有更新。因此,我将一个基本算法组合在一起,该算法通过 while 循环将另一个变量递增一个变量,直到达到某个数字。

counter=1
counter2=0

while [[ counter2 < 10 ]]; do
   counter2=$(($counter2+$counter))
   echo $counter
   echo $counter2
done 

我运行脚本。什么也没做。我将其设置<>仅用于踢球,并且重复输出以下内容会发生无限循环:

1
0
1
0

永远永远,直到我停止它。所以很明显变量没有改变。为什么?我觉得自己像个白痴,因为它一定是我忽略的一些愚蠢的东西。为什么,当我<有时,它也不是无限循环?为什么它根本不打印任何东西?如果counter2总是小于 10,为什么它不一直持续下去呢?

提前谢谢各位。

编辑:嗯,我意识到为什么当检查是<......我应该一直使用它$counter2而不是仅仅counter2为了获得counter2. 但现在它只是输出:

1
2

就是这样......我觉得自己像个笨蛋。

4

3 回答 3

4

在 内$((...)),不要使用印记 ( $)。

counter2=$((counter2+counter))
于 2012-04-10T01:50:51.383 回答
4

If this is all bash (100% sure) then you could use declare -i in order to explicitly set type of your variables and then your code will be as simple as :

declare -i counter=1
declare -i counter2=0

while [[ $counter2 -lt 10 ]]; do
   counter2=$counter2+$counter
   echo $counter
   echo $counter2
done

EDIT: In bash, you can do arithmatic comparison with double paranethesis. So, your while can be written as:

while (($counter2 <  10)) ; do
于 2012-04-10T01:55:02.390 回答
1

In bash, you can use c-like for loops:

for (( counter2=0; counter2<10; counter2+=counter ))
do
   echo $counter": "$counter2
done

Often you will find this construct more appealing to use:

for counter2 in {0..9}
do
    echo $counter": "$counter2
done
于 2012-04-10T02:32:30.063 回答