微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

bash – 修改while循环中的变量不记住

在下面的程序中,如果我将变量$ foo设置为第一个if语句中的值1,它的意思是它的值在if语句之后被记住。但是,当我将一个相同的变量设置为一个if语句中的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中循环执行的。因此,对子变量退出后,对变量所做的任何更改都不可用。

相反,你可以使用here string重写while循环在主shell进程中;只有echo -e $行将在子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")"

原文地址:https://www.jb51.cc/bash/391978.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐