Let's say I want to repeat the same string of environment variables before running various incantations of a command
if [[ some_thing ]]; then
TZ=GMT LC_ALL=C LONG_ENV_VAR=foo my_command
elif [[ some_other_thing ]]; then
TZ=GMT LC_ALL=C LONG_ENV_VAR=foo my_command --with-arg
else
TZ=GMT LC_ALL=C LONG_ENV_VAR=foo my_command --with-other-arg
fi
Is there a way to combine those? Some options
-
Set them via
export
export TZ=GMT export LC_ALL=C export LONG_ENV_VAR=foo if [[ ]] # ...
This works but I would rather not have them continue to be set in the environment.
-
Attempt to create a variable variable!
local cmd_args="TZ=GMT LC_ALL=C LONG_ENV_VAR=foo"
Unfortunately when I tried to run this via:
$cmd_args my_command
I got
TZ=GMT: command not found
. -
Just list them all out every time.
I also tried Googling for this, but "environment variable variable" isn't the easiest term to search for and I didn't get anywhere. Is there a fix for what I'm trying to do in #2? or am I stuck with some version of #1 and unsetting the vars afterwards?
Best Answer
I might use a subshell for this:
That allows you to clearly set the variables once; have them present for anything you run inside the subshell, and also not be present in the main shell's environment.