[英]source a file containing environment variables including “dash” character in bash?
I'm using bash and have a file called x.config
that contains the following: 我正在使用bash,并且有一个名为
x.config
的文件,其中包含以下内容:
MY_VAR=Something1
ANOTHER=Something2
To load these as environment variables I just use source: 要将它们加载为环境变量,我只使用source:
$ source x.config
But this doesn't work if MY_VAR
is called MY-VAR
: 但这如果
MY_VAR
被称为MY-VAR
则MY_VAR
:
MY-VAR=Something1
ANOTHER=Something2
If I do the same thing I get: 如果我做同样的事情,我会得到:
x.config:1: command not found: MY-VAR=Something1
I've tried escaping -
and a lot of other things but I'm stuck. 我已经尝试过转义
-
以及其他很多事情,但是我被卡住了。 Does anyone know a workaround for this? 有谁知道解决方法?
A pure bash
workaround that might work for you is to re-run the script using env
to set the environment. 一个可能对您
bash
的纯bash
解决方法是使用env
设置环境来重新运行脚本。 Add this to the beginning of your script. 将此添加到脚本的开头。
if [[ ! -v myscript_env_set ]]; then
export myscript_env_set=1
readarray -t newenv < x.config
exec env "${newenv[@]}" "$0" "$@"
fi
# rest of the script here
This assumes that x.config
doesn't contain anything except variable assignments. 假设
x.config
除了变量分配外不包含任何其他内容。 If myscript_env_set
is not in the current environment, put it there so that the next invocation skips this block. 如果
myscript_env_set
不在当前环境中,请将其放在此处,以便下一次调用跳过此块。 Then read the assignments into an array to pass to env
. 然后将分配读入数组以传递给
env
。 Using exec
replaces the current process with another invocation of the script, but with the desired variables in the environment. 使用
exec
将用另一个脚本调用替换当前进程,但是会使用环境中所需的变量。
A dash ( -
) in an environment variable is not portable, and as you noticed, will cause a lot of problems. 环境变量中的破折号(
-
)不可移植,并且如您所注意到的,会引起很多问题。 You can't set these from bash. 您无法通过bash进行设置。 Fix the application you want to invoke .
修复您要调用的应用程序 。
That being said, if you can't change the target app, you can do this from python: 话虽如此,如果您不能更改目标应用程序,则可以从python进行操作:
#!/usr/bin/python
import os
with open('x.config') as f:
for line in f:
name, value = line.strip().split('=')
os.environ[name] = value
os.system('/path/to/your/app')
This is a very simplistic config reader, and for a more complex syntax you might want to use ConfigParser
. 这是一个非常简单的配置读取器,对于更复杂的语法,您可能需要使用
ConfigParser
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.