Bash:在while循环后保留变量的值

标签 bash

我需要保留 TEMP_FLAG 的值在我的 while 循环结束之后。

#!/bin/bash

TEMP_FLAG=false

# loop over git log and set variable
git log --pretty="%H|%s" --skip=1 |
    while read commit; do 

        # do stuff like parsing the commit...

        # set variable     
        TEMP_FLAG=true 
    done

echo "$TEMP_FLAG" # <--- evaluates to false :(

我知道我的问题是由管道 git log 引起的到 while 循环,它会生成一个子 shell,但不会返回我更新的变量。

但是,有没有办法在不改变管道的情况下实现我的预期行为?

最佳答案

当您使用管道时,您会自动创建子 shell,以便 shell 可以连接输入和输出。这意味着您无法修改父环境,因为您现在处于子进程中。

正如 anubhava 所说,您可以通过使用进程替换来重新构造循环以避免管道:

while read commit; do
    TEMP_FLAG=true
done < <( git log --pretty="%H|%s" --skip=1 )

printf "%s\n" "$TEMP_FLAG"

关于Bash:在while循环后保留变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098271/

相关文章:

bash - expr 和 if 在 bash 中

linux - bash 信号陷阱将覆盖其 nohup 子命令的信号?

arrays - 狂欢 : Use a variable as an associative array name

linux - Grep 在 Bash 脚本中没有这样的文件或目录错误,我应该插入等待命令吗?

bash - 将 bash $$ 值保存在变量中

linux - 我如何计算 shell 脚本 linux bash 中有多少个挂起的进程

bash - 多个变量的列总和

arrays - 使用 IFS 排列的 Bash 字符串

bash - 用 bash 读取子目录

linux - 使用点空格与点斜线执行文件