linux - 为什么这个变量没有被改变?

标签 linux bash

<分区>

我有一个较大的脚本,但这个较小的脚本显示了问题:

#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   ls | while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done
fi
echo "this should NOT be 0 --> $x" 

如果变量设置在 while 循环之外,那么它会像我预期的那样工作。 bash 版本是 3.2.25(1)-release (x86_64-redhat-linux-gnu)。如果这是显而易见的事情,我会觉得很愚蠢。

最佳答案

设置为 5 的 x 在子 shell 中(因为它是管道的一部分),子 shell 中发生的事情不会影响父 shell。

您可以通过在 bash 中使用进程替换来避免子 shell 并获得您期望的结果:

#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done < <(ls)
fi
echo "this should NOT be 0 --> $x"

现在 while 循环是主 shell 进程的一部分(只有 ls 在子进程中)所以变量 x受到影响。

我们可以下次再讨论解析 ls 输出的优点;这在很大程度上是问题中的问题。

另一种选择是:

#!/bin/bash
x=0
if [[ $x == 0 ]]
then
   ls | 
   {
   while read L
   do
     x=5
     echo "this is a file $L and this is now set to five --> $x"
   done
   echo "this should NOT be 0 --> $x"
   }
fi
echo "this should be 0 still, though --> $x"

关于linux - 为什么这个变量没有被改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491055/

相关文章:

linux - 如何获得最常出现的 unix 实用程序

linux - Unix 重命名文件

linux - init.d 脚本停止 echo 管道到 grep 输出到终端

python - 在 Ubuntu 10.04 中安装 Dropbox python SDK

python - 如何使用 ansi 转义码为 python 中的特定字符单元着色,其中字符单元位置由变量确定

linux - 如何安装 Fortran 编译器 (gcc42-fortran)

c++ - 加速单个文件的 gcc 编译

bash - Windows 10 Bash (Ubuntu) - 如何向上滚动?

bash - 找出 Google Cloud SDK 的安装位置

linux - xvfb 和 xvfb-run 之间有区别吗?