Scribbled summary of a thing I learned this week.

I had code like this used to source settings from scripts stored in other folders:

find /etc/application -name "*.sh" -type f |while read FILE; do
  source $FILE

exec /path/to/application/

Inside /etc/application/ I’d have some code like this:

export SOME_VARIABLE="some value"

Some oddness seemed to be happening though, when the application was running it would never see the value of SOME_VARIABLE.

This is because I didn’t know bash pipes run in subshells, so the subshell is sourcing the $FILE. Subshells can’t modify the environment of their parent process.

To get this to work the source needs to happen in the main process, so the code needs to be rewritten something like this to use input redirection:

while read FILE; do
  source $FILE
done < <(find /etc/application  -name "*.sh" -type f)

exec /path/to/application/

Now the application can see the environment variables it’s expecting. Yay!

written by
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO
curl -LO
gpg --verify{.asc,}