在下面的程序中,如果我将变量$foo设置为第一个if语句中的值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)
我使用stderr在循环内存储,并从循环外读取。
这里var i最初被设置并在循环中读取为1。
# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value
f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
echo $s > /dev/null; # some work
echo $i > 2
let i++
done;
read -r i < 2
echo $i
或者使用heredoc方法来减少子shell中的代码量。
注意,迭代的i值可以在while循环之外读取。
i=1
while read -r s;
do
echo $s > /dev/null
let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i
echo -e $lines | while read line
...
done
while循环在子shell中执行。因此,一旦子shell退出,您对变量所做的任何更改都将不可用。
相反,你可以使用一个here字符串来重写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")"
在分配行时,可以通过立即展开反斜杠序列来消除上面here-string中相当难看的echo。美元的…的引用形式可以用在这里:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
我使用stderr在循环内存储,并从循环外读取。
这里var i最初被设置并在循环中读取为1。
# reading lines of content from 2 files concatenated
# inside loop: write value of var i to stderr (before iteration)
# outside: read var i from stderr, has last iterative value
f=/tmp/file1
g=/tmp/file2
i=1
cat $f $g | \
while read -r s;
do
echo $s > /dev/null; # some work
echo $i > 2
let i++
done;
read -r i < 2
echo $i
或者使用heredoc方法来减少子shell中的代码量。
注意,迭代的i值可以在while循环之外读取。
i=1
while read -r s;
do
echo $s > /dev/null
let i++
done <<EOT
$(cat $f $g)
EOT
let i--
echo $i