Counter increment in Bash loop not working

前端 未结 13 2388
庸人自扰
庸人自扰 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:22

    First, you are not increasing the counter. Changing COUNTER=$((COUNTER)) into COUNTER=$((COUNTER + 1)) or COUNTER=$[COUNTER + 1] will increase it.

    Second, it's trickier to back-propagate subshell variables to the callee as you surmise. Variables in a subshell are not available outside the subshell. These are variables local to the child process.

    One way to solve it is using a temp file for storing the intermediate value:

    TEMPFILE=/tmp/$$.tmp
    echo 0 > $TEMPFILE
    
    # Loop goes here
      # Fetch the value and increase it
      COUNTER=$[$(cat $TEMPFILE) + 1]
    
      # Store the new value
      echo $COUNTER > $TEMPFILE
    
    # Loop done, script done, delete the file
    unlink $TEMPFILE
    

提交回复
热议问题