相关疑难解决方法(0)

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

在下面的程序中,如果我$foo在第一个if语句中将变量设置为值1 ,那么它的作用就是在if语句之后记住它的值.但是,当我将同一个变量设置ifwhile语句内部的值2时,它在while循环之后就被遗忘了.它的行为就像我$foowhile循环中使用某种变量的副本而我只修改那个特定的副本.这是一个完整的测试程序:

#!/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 …
Run Code Online (Sandbox Code Playgroud)

bash scope sh while-loop

168
推荐指数
3
解决办法
15万
查看次数

标签 统计

bash ×1

scope ×1

sh ×1

while-loop ×1