A variable modified inside a while loop is not remembered

后端 未结 8 2150
挽巷
挽巷 2020-11-21 05:06

In the following program, if I set the variable $foo to the value 1 inside the first if statement, it works in the sense that its value is remember

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 05:16

    echo -e $lines | while read line 
        ...
    done
    

    The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

    Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

    while read line
    do
        if [[ "$line" == "second line" ]]
        then
            foo=2
            echo "Variable \$foo updated to $foo inside if inside while loop"
        fi
        echo "Value of \$foo in while loop body: $foo"
    done <<< "$(echo -e "$lines")"
    

    You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

    lines=$'first line\nsecond line\nthird line'
    while read line; do
        ...
    done <<< "$lines"
    

提交回复
热议问题