我需要保留 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/