Issue
I have a function where I tried to export some env vars:
env -0 | while IFS='=' read -r -d '' env_var_name env_var_value; do
# Some logic here, then:
export MY_ENV_VAR=hello
done
However, I just noticed that export
and unset
do not work inside this loop. What's the best way to perform these exports if I can't do them inside the loop? Store them somewhere and execute them outside the loop?
Solution
The loop isn't the issue. The problem is actually the pipe. When you pipe to a command, a subshell is created and any variables set inside of that subshell will go away when it exits. You can work around this using process substitution:
while IFS='=' read -r -d '' env_var_name env_var_value; do
# Some logic here, then:
export MY_ENV_VAR=hello
done < <(env -0)
Answered By - jordanm