Bash:在while循环后保留变量的值 [英] Bash: Retain variable's value after while loop
问题描述
我的while循环结束后,我需要保留TEMP_FLAG
的值.
I need to retain the value of TEMP_FLAG
after my while loop ends.
#!/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不会返回我的更新变量.
I know that my issue is caused by piping the git log
to the while loop, which spawns a subshell that doesn't give back my updated variable.
但是,有一种方法可以在不更改管道的情况下实现我的预期行为吗?
However, is there a way get my intended behavior without changing the pipe?
推荐答案
使用管道时,您会自动创建子Shell,以便输入和输出可以被该Shell连接.这意味着您无法修改父环境,因为您现在处于子进程中.
When you use a pipe you are automatically creating subshells so that the input and output can be hooked up by the shell. That means that you cannot modify the parent environment, because you're now in a child process.
就像anubhava所说的那样,您可以像下面这样使用进程替换来重新构造循环以避免管道:
As anubhava said though, you can reformulate the loop to avoid the pipe by using process substitution like so:
while read commit; do
TEMP_FLAG=true
done < <( git log --pretty="%H|%s" --skip=1 )
printf "%s\n" "$TEMP_FLAG"
这篇关于Bash:在while循环后保留变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!