A variable modified inside a while loop is not remembered

后端 未结 8 2173
挽巷
挽巷 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:24

    Though this is an old question and asked several times, here's what I'm doing after hours fidgeting with here strings, and the only option that worked for me is to store the value in a file during while loop sub-shells and then retrieve it. Simple.

    Use echo statement to store and cat statement to retrieve. And the bash user must chown the directory or have read-write chmod access.

    #write to file
    echo "1" > foo.txt
    
    while condition; do 
        if (condition); then
            #write again to file
            echo "2" > foo.txt      
        fi
    done
    
    #read from file
    echo "Value of \$foo in while loop body: $(cat foo.txt)"
    

提交回复
热议问题