代码
使用管道会创建子shell。
lines="first line\nsecond line\nthird line"
foo=0
echo -e $lines | while read line
do
echo line: $line
if [[ "$line" == "second line" ]]
then
foo=2 # 此处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 "foo=$foo" #输出结果foo=0
here-strings语法: command <<< "WORD"
foo=0
lines="first line\nsecond line\nthird line"
while read line
do
echo line $line
if [[ "$line" == "second line" ]]
then
foo=2 # 此处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 -e "$lines") 也可
echo "foo=$foo" #输出结果foo=2
process substitution语法: command1 < <(command2)
注意:< <内有空格,第二个<后不能有空格
foo=0
lines="first line\nsecond line\nthird line"
while read line
do
echo line $line
if [[ "$line" == "second line" ]]
then
foo=2 # 此处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 "foo=$foo" #输出结果foo=2
foo=0
lines=$(
cat << EOF
first line\nsecond line
third line
EOF
)
echo lines:$lines
while read line
do
echo line $line
if [[ "$line" == "second line" ]]
then
foo=2 # 2被赋值给foo
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 "foo=$foo" # 输出foo=2
foo=0
cat << EOF > lines.txt
first line
second line
third line\nfourth line
EOF
cat lines.txt
while read line
do
echo line $line
if [[ "$line" == "second line" ]]
then
foo=2 # 2被赋值给foo
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done < lines.txt
echo "foo=$foo" # 输出foo=2
lines.txt文件的内容如下
first line
second line
third line\nfourth line
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)