linux - 不能在 bash 中使用 while 和 pipe 中的变量

标签 linux bash environment-variables pipe

我有这样的代码

var="before"  
echo "$someString" | sed '$someRegex' | while read line 
do
    if [ $condition ]; then
        var="after"
        echo "$var" #first echo
    fi 
done 
echo "$var" #second echo

这里第一个回显打印“之后”,第二个是“之前”。如何在“之后”进行第二次回显打印。我认为这是因为管道购买我不知道怎么弄清楚。

感谢任何解决方案...

答案编辑:

我改正了它,它工作正常。感谢尤金的有用回答

var="before"  
while read line 
do
    if [ $condition ]; then
        var="after"
        echo "$var" #first echo
    fi 
done < <(echo "$someString" | sed '$someRegex')
echo "$var" #second echo

最佳答案

此行为的原因是 while 循环在作为管道的一部分时在子 shell 中运行。对于上面的 while 循环,创建了一个新的子 shell,它有自己的变量 var 副本。

有关可能的解决方法,请参阅本文:I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? .

关于linux - 不能在 bash 中使用 while 和 pipe 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572411/

相关文章:

linux - 使用 flex 生成的文件时出现问题

regex - 使用正则表达式在 bash 中搜索和替换

c++ - 执行 bash shell 命令并提取输出 --> 无效文件错误

batch-file - 如何使用变量值作为另一个变量(批处理文件)的名称?

python - 如何使用python设置环境变量?

c++ - 自行卸载的 Linux 共享库

linux - mkdir 中的脚本输出错误

c++ - 如何在 C++ 中使用 system() 抛出异常?

bash - awk 或 Sed : Replace text between special characters (delimiters)

c# - ProcessStartInfo.EnvironmentVariables 和 ProcessStartInfo.Environment 之间有什么区别