Kev*_*rke 6 bash environment-variables
假设我想在运行命令的各种咒语之前重复相同的环境变量字符串
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
Run Code Online (Sandbox Code Playgroud)
有没有办法将它们结合起来?一些选项
通过设置它们 export
export TZ=GMT
export LC_ALL=C
export LONG_ENV_VAR=foo
if [[ ]] # ...
Run Code Online (Sandbox Code Playgroud)
这有效,但我宁愿不让它们继续在环境中设置。
尝试创建一个可变变量!
local cmd_args="TZ=GMT LC_ALL=C LONG_ENV_VAR=foo"
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我尝试通过以下方式运行它时:
$cmd_args my_command
Run Code Online (Sandbox Code Playgroud)
我得到了TZ=GMT: command not found。
每次都把它们都列出来。
我也为此尝试过谷歌搜索,但“环境变量变量”不是最容易搜索的术语,我没有找到任何地方。我在 #2 中尝试做的事情有解决方法吗?还是我坚持使用 #1 的某个版本并在之后取消设置变量?
Jef*_*ler 12
我可能会为此使用子shell:
(
export TZ=GMT LC_ALL=C LONG_ENV_VAR=foo
if [[ some_thing ]]; then
exec my_command
…
fi
)
Run Code Online (Sandbox Code Playgroud)
这允许您一次清楚地设置变量;让它们出现在您在子 shell 中运行的任何内容中,并且也不出现在主 shell 的环境中。
ter*_*don 12
有多种方法可以做到这一点。就个人而言,我发现函数更清晰:
run_this(){
TZ=GMT LC_ALL=C LONG_ENV_VAR=foo "$@"
}
if [[ some_thing ]]; then
run_this my_command
elif [[ some_other_thing ]]; then
run_this my_command --with-arg
else
run_this my_command --with-other-arg
fi
Run Code Online (Sandbox Code Playgroud)
点 2. 可以通过env:
local env_args="greppable1=foo greppable2=bar"
env $env_args perl -E 'say for grep /greppable/, keys %ENV'
Run Code Online (Sandbox Code Playgroud)
但是,如果任何 env args 中有空格,bash 分词规则可能会使这变得复杂。