Counter increment in Bash loop not working

前端 未结 13 2322
庸人自扰
庸人自扰 2020-12-02 05:31

I have the following simple script where I am running a loop and want to maintain a COUNTER. I am unable to figure out why the counter is not updating. Is it du

13条回答
  •  醉梦人生
    2020-12-02 06:10

    This is all you need to do:

    $((COUNTER++))
    

    Here's an excerpt from Learning the bash Shell, 3rd Edition, pp. 147, 148:

    bash arithmetic expressions are equivalent to their counterparts in the Java and C languages.[9] Precedence and associativity are the same as in C. Table 6-2 shows the arithmetic operators that are supported. Although some of these are (or contain) special characters, there is no need to backslash-escape them, because they are within the $((...)) syntax.

    ..........................

    The ++ and - operators are useful when you want to increment or decrement a value by one.[11] They work the same as in Java and C, e.g., value++ increments value by 1. This is called post-increment; there is also a pre-increment: ++value. The difference becomes evident with an example:

    $ i=0
    $ echo $i
    0
    $ echo $((i++))
    0
    $ echo $i
    1
    $ echo $((++i))
    2
    $ echo $i
    2
    

    See http://www.safaribooksonline.com/a/learning-the-bash/7572399/

提交回复
热议问题