bash - A variable modified inside a while loop is not remembered -
in following program, if set variable $foo
value 1 inside first if
statement, works in sense value remembered after if statement. however, when set same variable value 2 inside if
inside while
statement, it's forgotten after while
loop. it's behaving i'm using sort of copy of variable $foo
inside while
loop , modifying particular copy. here's complete test program:
#!/bin/bash set -e set -u foo=0 bar="hello" if [[ "$bar" == "hello" ]] foo=1 echo "setting \$foo 1: $foo" fi echo "variable \$foo after if statement: $foo" lines="first line\nsecond line\nthird line" echo -e $lines | while read line if [[ "$line" == "second line" ]] foo=2 echo "variable \$foo updated $foo inside if inside while loop" fi echo "value of \$foo in while loop body: $foo" done echo "variable \$foo after while loop: $foo" # output: # $ ./testbash.sh # setting $foo 1: 1 # variable $foo after if statement: 1 # value of $foo in while loop body: 1 # variable $foo updated 2 inside if inside while loop # value of $foo in while loop body: 2 # value of $foo in while loop body: 2 # variable $foo after while loop: 1 # bash --version # gnu bash, version 4.1.10(4)-release (i686-pc-cygwin)
echo -e $lines | while read line ... done
the while
loop executed in subshell. changes variable not available once subshell exits.
instead can use here string re-write while loop in main shell process; echo -e $lines
run in subshell:
while read line if [[ "$line" == "second line" ]] foo=2 echo "variable \$foo updated $foo inside if inside while loop" fi echo "value of \$foo in while loop body: $foo" done <<< "$(echo -e "$lines")"
Comments
Post a Comment