Bash: Retain variable's value after while loop

2020-02-07 08:16发布

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 :(

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?

标签: bash
1条回答
疯言疯语
2楼-- · 2020-02-07 08:39

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.

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"
查看更多
登录 后发表回答