shell为管道创建subshell 2022-07-20

2022-07-20  本文已影响0人  9_SooHyun

问题源
https://stackoverflow.com/questions/16854280/a-variable-modified-inside-a-while-loop-is-not-remembered

运行以下shell会发现,变量foo在经历了循环后并没有变更成预期的值。这是因为shell会为管道| 创建子进程,父子进程通过管道通信。子进程的foo确实被改了,但父进程的foo确实没被改

#!/bin/bash

set -e
set -u 
foo=0
bar="hello"  
if [[ "$bar" == "hello" ]]
then
    foo=1
    echo "Setting \$foo to 1: $foo"
fi

echo "Variable \$foo after if statement: $foo"   
lines="first line\nsecond line\nthird line" 
echo -e $lines | 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 "Variable \$foo after while loop: $foo"

# Output:
# $ ./testbash.sh
# Setting $foo to 1: 1
# Variable $foo after if statement: 1
# Value of $foo in while loop body: 1
# Variable $foo updated to 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)
上一篇 下一篇

猜你喜欢

热点阅读