Search code examples
linuxbashloopsinfinite-loopupdating

How to update a variable value from a loop A to another loop B - in bash


I am increasing the value of a variable in a first loop and using it in a second loop.

My problem: the variable doesn't change in the second loop. (It's an example, I know that I can move the code that changes the value from the loop into the function but I have a program with multiple functions and multiple loops).

My question: how to update the value of a variable (increasing inside a first while loop) in a second while loop?

Here is an illustration (First loop is increasing the counter_value but the second loop stick to "1") :

#!/bin/bash

counter_value="1"

function Print_counter_value () {
    echo $counter_value ; }

#_____FIRST LOOP_____
while : ; do # infinite loop
      #echo first loop works
      counter_value=$[$counter_value+1]
      echo $counter_value 1st_loop & sleep 2
done &

#_____SECOND LOOP_____
while : ; do # infinite loop
      #echo second loop works
      Print_counter_value & sleep 1
done &

Thank you!


Solution

  • The line that increments the variable:

    ((counter_value++))
    

    There's no need to put the second loop into the background. Saving the variable to a file is a little clumbsy, but it works.

    #!/bin/bash
    
    counter_value=1
    file="/tmp/temp$$"
    echo "counter_value=$counter_value" > "$file"
    
    function Print_counter_value () {
        echo $counter_value ; }
    
    #_____FIRST LOOP_____
    while : ; do # infinite loop
        . "$file"
        ((counter_value++))
        echo "counter_value=$counter_value" > "$file"
        sleep 2
    done &
    
    #_____SECOND LOOP_____
    while : ; do # infinite loop
        . "$file"
        Print_counter_value & sleep 1
    done