1

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?

rmf
  • 625
  • 2
  • 9
  • 39
  • 2
    See: [Why variable values are lost after terminating the loop in bash?](https://stackoverflow.com/q/26144029/3776858) or [A variable modified inside a while loop is not remembered](https://stackoverflow.com/q/16854280/3776858) – Cyrus Jun 18 '21 at 16:32

1 Answers1

6

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)
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • Thanks @jordanm, quick follow on: I'm calling this loop is a script then piping the script to another: `source export-vars.sh |& format-log.sh`. The `source export.vars.sh` works on its own, but not when I pipe it to `format-log.sh` - any ideas how to fix? – rmf Jun 18 '21 at 16:44
  • @Rory Other than removing the format-log.sh, I can't think of a work-around for that situation off-hand – jordanm Jun 18 '21 at 16:52