242

在下面的程序中,如果我$foo在第一个语句中将变量设置为值 1 if,则它的工作原理是在 if 语句之后记住它的值。if但是,当我在语句中的 an 中将相同的变量设置为值 2 时,它在循环while后被遗忘了。它的行为就像我在循环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 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)
4

8 回答 8

297
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")"

您可以echo通过在分配lines. 引用的$'...'形式可以在那里使用:

lines=$'first line\nsecond line\nthird line'
while read line; do
    ...
done <<< "$lines"
于 2013-05-31T09:40:30.467 回答
53

更新#2

解释在 Blue Moons 的回答中。

替代解决方案:

排除echo

while read line; do
...
done <<EOT
first line
second line
third line
EOT

在 here-is-the-document 中添加回声

while read line; do
...
done <<EOT
$(echo -e $lines)
EOT

echo在后台运行:

coproc echo -e $lines
while read -u ${COPROC[0]} line; do 
...
done

显式重定向到文件句柄(注意< <!中的空格):

exec 3< <(echo -e  $lines)
while read -u 3 line; do
...
done

或者只是重定向到stdin

while read line; do
...
done < <(echo -e  $lines)

一个用于chepner(消除echo):

arr=("first line" "second line" "third line");
for((i=0;i<${#arr[*]};++i)) { line=${arr[i]}; 
...
}

可以将变量$lines转换为数组,而无需启动新的子 shell。字符\n必须转换为某些字符(例如,真正的换行符)并使用 IFS(内部字段分隔符)变量将字符串拆分为数组元素。这可以像这样完成:

lines="first line\nsecond line\nthird line"
echo "$lines"
OIFS="$IFS"
IFS=$'\n' arr=(${lines//\\n/$'\n'}) # Conversion
IFS="$OIFS"
echo "${arr[@]}", Length: ${#arr[*]}
set|grep ^arr

结果是

first line\nsecond line\nthird line
first line second line third line, Length: 3
arr=([0]="first line" [1]="second line" [2]="third line")
于 2013-05-31T10:28:38.757 回答
12

您是第 742342 个询问此bash 常见问题解答的用户。答案还描述了由管道创建的子shell中设置的变量的一般情况:

E4)如果我将命令的输出通过管道传输到read variable,为什么$variable在读取命令完成时输出不显示?

这与 Unix 进程之间的父子关系有关。它影响在管道中运行的所有命令,而不仅仅是对read. 例如,将命令的输出while传递到重复调用的循环read中将导致相同的行为。

管道的每个元素,甚至是内置函数或 shell 函数,都在单独的进程中运行,即运行管道的 shell 的子进程。子进程不能影响其父进程的环境。当read命令将变量设置为输入时,该变量仅在子 shell 中设置,而不是在父 shell 中。当 subshel​​l 退出时,变量的值会丢失。

许多以结尾的管道read variable可以转换为命令替换,这将捕获指定命令的输出。然后可以将输出分配给一个变量:

grep ^gnu /usr/lib/news/active | wc -l | read ngroup

可以转换成

ngroup=$(grep ^gnu /usr/lib/news/active | wc -l)

不幸的是,这不会像 read 在给定多个变量参数时那样在多个变量之间拆分文本。如果您需要这样做,您可以使用上面的命令替换将输出读入变量并使用 bash 模式删除扩展运算符分割变量,或者使用以下方法的一些变体。

说 /usr/local/bin/ipaddr 是以下 shell 脚本:

#! /bin/sh
host `hostname` | awk '/address/ {print $NF}'

而不是使用

/usr/local/bin/ipaddr | read A B C D

要将本地机器的 IP 地址分成单独的八位字节,请使用

OIFS="$IFS"
IFS=.
set -- $(/usr/local/bin/ipaddr)
IFS="$OIFS"
A="$1" B="$2" C="$3" D="$4"

但是请注意,这将改变外壳的位置参数。如果你需要它们,你应该在这样做之前保存它们。

这是一般方法——在大多数情况下,您不需要将 $IFS 设置为不同的值。

其他一些用户提供的替代方案包括:

read A B C D << HERE
    $(IFS=.; echo $(/usr/local/bin/ipaddr))
HERE

并且,在流程替代可用的情况下,

read A B C D < <(IFS=.; echo $(/usr/local/bin/ipaddr))
于 2013-05-31T16:09:22.880 回答
4

嗯...我几乎发誓这适用于原始的 Bourne shell,但现在无法访问运行副本来检查。

然而,这个问题有一个非常简单的解决方法。

将脚本的第一行更改为:

#!/bin/bash

#!/bin/ksh

瞧!假设您安装了 Korn shell,则在管道末尾读取就可以了。

于 2014-10-20T18:56:41.577 回答
2

我使用 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
于 2020-07-15T21:34:59.263 回答
1

这是一个有趣的问题,涉及到 Bourne shell 和 subshel​​l 中的一个非常基本的概念。在这里,我通过进行某种过滤提供了一个与以前的解决方案不同的解决方案。我将举一个在现实生活中可能有用的例子。这是用于检查下载文件是否符合已知校验和的片段。校验和文件如下所示(仅显示 3 行):

49174 36326 dna_align_feature.txt.gz
54757     1 dna.txt.gz
55409  9971 exon_transcript.txt.gz

外壳脚本:

#!/bin/sh

.....

failcnt=0 # this variable is only valid in the parent shell
#variable xx captures all the outputs from the while loop
xx=$(cat ${checkfile} | while read -r line; do
    num1=$(echo $line | awk '{print $1}')
    num2=$(echo $line | awk '{print $2}')
    fname=$(echo $line | awk '{print $3}')
    if [ -f "$fname" ]; then
        res=$(sum $fname)
        filegood=$(sum $fname | awk -v na=$num1 -v nb=$num2 -v fn=$fname '{ if (na == $1 && nb == $2) { print "TRUE"; } else { print "FALSE"; }}')
        if [ "$filegood" = "FALSE" ]; then
            failcnt=$(expr $failcnt + 1) # only in subshell
            echo "$fname BAD $failcnt"
        fi
    fi
done | tail -1) # I am only interested in the final result
# you can capture a whole bunch of texts and do further filtering
failcnt=${xx#* BAD } # I am only interested in the number
# this variable is in the parent shell
echo failcnt $failcnt
if [ $failcnt -gt 0 ]; then
    echo $failcnt files failed
else
    echo download successful
fi

父外壳和子外壳通过 echo 命令进行通信。您可以为父 shell 选择一些易于解析的文本。这种方法并没有打破你正常的思维方式,只是你需要做一些后期处理。您可以使用 grep、sed、awk 等来执行此操作。

于 2018-03-07T04:02:28.157 回答
0

一个非常简单的方法怎么样

    +call your while loop in a function 
     - set your value inside (nonsense, but shows the example)
     - return your value inside 
    +capture your value outside
    +set outside
    +display outside


    #!/bin/bash
    # set -e
    # set -u
    # No idea why you need this, not using here

    foo=0
    bar="hello"

    if [[ "$bar" == "hello" ]]
    then
        foo=1
        echo "Setting  \$foo to $foo"
    fi

    echo "Variable \$foo after if statement: $foo"

    lines="first line\nsecond line\nthird line"

    function my_while_loop
    {

    echo -e $lines | while read line
    do
        if [[ "$line" == "second line" ]]
        then
        foo=2; return 2;
        echo "Variable \$foo updated to $foo inside if inside while loop"
        fi

        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"
    return 2;
    fi

    # Code below won't be executed since we returned from function in 'if' statement
    # We aready reported the $foo var beint set to 2 anyway
    echo "Value of \$foo in while loop body: $foo"

done
}

    my_while_loop; foo="$?"

    echo "Variable \$foo after while loop: $foo"


    Output:
    Setting  $foo 1
    Variable $foo after if statement: 1
    Value of $foo in while loop body: 1
    Variable $foo after while loop: 2

    bash --version

    GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
    Copyright (C) 2007 Free Software Foundation, Inc.
于 2014-08-30T03:40:26.137 回答
0

虽然这是一个老问题并且被问了好几次,但这是我在几个小时后对here字符串坐立不安的事情,对我有用的唯一选择是在 while 循环子 shell 期间将值存储在文件中,然后检索它。简单的。

使用echo语句存储和cat语句检索。并且 bash 用户必须chown具有该目录或具有读写chmod权限。

#write to file
echo "1" > foo.txt

while condition; do 
    if (condition); then
        #write again to file
        echo "2" > foo.txt      
    fi
done

#read from file
echo "Value of \$foo in while loop body: $(cat foo.txt)"
于 2020-11-12T04:25:57.683 回答