bash 使用 while read 循环中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9548983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:42:45  来源:igfitidea点击:

Make use of variable from while read loop

bashvariables

提问by theta

In my bash script I use while readloop and a helper function fv():

在我的 bash 脚本中,我使用while read循环和辅助函数fv()

fv() {
    case "" in
    out) echo $VAR
    ;;
    *  ) VAR="$VAR "
    ;; 
    esac
}

cat "" | while read line
    do
        ...some processings...
        fv some-str-value
    done

echo "`fv out`"

in a hope that I can distil value from while readloop in a variable accessible in rest of the script. But above snippet is no good, as I get no output.

希望我可以从while read脚本其余部分可访问的变量中的循环中提取值。但是上面的代码片段不好,因为我没有输出。

Is there easy way to solve this - output string from this loop in a variable that would be accessible in rest of the script - without reformatting my script?

有没有简单的方法可以解决这个问题——这个循环的输出字符串在一个可以在脚本的其余部分访问的变量中——而不用重新格式化我的脚本?

回答by Kevin

As no one has explained to you whyyour code didn't work, I will.

由于没有人向您解释为什么您的代码不起作用,我会解释的。

When you use cat "$1" |, you are making that loop execute in a subshell. The VARvariable used in that subshell starts as a copy of VARfrom the main script, and any changes to it are limited to that copy (the subshell's scope), they don't affect the script's original VAR. By removing the useless use of cat, you remove the pipeline and so the loop is executed in the main shell, so it can (and does) alter the correct copy of VAR.

当您使用 时cat "$1" |,您正在使该循环在子shell 中执行。该VAR子shell中使用的变量VAR从主脚本的副本开始,对它的任何更改都仅限于该副本(子shell的范围),它们不会影响脚本的原始VAR. 通过删除cat无用使用,您删除了管道,因此循环在主 shell 中执行,因此它可以(并且确实)更改VAR.

回答by sgibb

Replace your while loop by while read line ; do ... ; done < $1:

将您的 while 循环替换为while read line ; do ... ; done < $1

#!/bin/bash

function fv
{
    case "" in
    out) echo $VAR
    ;;
    *  ) VAR="$VAR "
    ;; 
    esac
}

while read line
    do
        fv "$line\n"
    done < ""

echo "$(fv out)"

回答by Ignacio Vazquez-Abrams

Stop piping to read.

停止管道阅读。

done < ""