加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 16:41:04 所属栏目:安全 来源:网络整理
导读:在下面的程序中,如果我将变量$ foo设置为第一个if语句中的值1,它的意思是它的值在if语句之后被记
在下面的程序中,如果我将变量$ 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 linensecond linenthird 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")"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读