Skip to content
Advertisement

Bash export variables but only for current command

I want to load some environment variables from a file before running a node script, so that the script has access to them. However, I don’t want the environment variables to be set in my shell after the script is done executing.

I can load the environment variables like this:

export $(cat app-env-vars.txt | xargs) && node my-script.js

However, after the command is run, all of the environment variables are now set in my shell.

I’m asking this question to answer it, since I figured out a solution but couldn’t find an answer on SO.

Advertisement

Answer

If you wrap the command in parentheses, the exports will be scoped to within those parens and won’t pollute the global shell namespace:

(export $(cat app-env-vars.txt | xargs) && node my-script.js)

Echo’ing one of the environment variables from the app.env file after executing the command will show it as empty.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement