bash - 在 while 循环内修改的变量不会被记住

标签 bash while-loop scope sh

在下面的程序中,如果我在第一个 if 语句中将变量 $foo 设置为值 1,那么它的工作原理是在之后记住它的值if 语句。但是,当我在 while 语句内的 if 中将同一变量设置为值 2 时,它在 while 循环之后被遗忘。它的行为就像我在 while 循环中使用变量 $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)

最佳答案

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

while 循环在子 shell 中执行。因此,一旦子 shell 退出,您对变量所做的任何更改都将不可用。

您可以使用 here string重写 while 循环以使其位于主 shell 进程中;只有 echo -e $lines 会在子 shell 中运行:

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")"

您可以通过在分配时立即展开反斜杠序列来消除上面字符串中相当难看的echo。可以在此处使用 $'...' 形式的引用:

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

关于bash - 在 while 循环内修改的变量不会被记住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37273933/

相关文章:

php - 有没有更有效的方法来编写嵌套的 While 循环?

java - 接受输入时无休止的java循环

java - java程序中if语句的作用域错误

javascript - jQuery全局选择 "cache"

linux - 在 bash 中查找和替换

bash - 从 bash 脚本调用 grunt.js 时出现问题

java - 计算用户控制循环程序中的平均数

javascript - 高阶函数的 MongoDB MapReduce 作用域

bash -/bin/bash -c 与直接执行命令有何不同?

bash - 通过Oozie Shell脚本运行配置单元查询时未找到表异常