Bash - 导出带有特殊字符 ($) 的环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43495673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash - export environment variables with special characters ($)
提问by User
I'm parsing a file with key=value
data and then export them as environment variables. My solution works, but not with special characters, example:
我正在解析带有key=value
数据的文件,然后将它们导出为环境变量。我的解决方案有效,但不适用于特殊字符,例如:
.data
。数据
VAR1=abc
VAR2=d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^
script.sh
脚本文件
#!/bin/bash
while IFS="=" read -r key value; do
case "$key" in
'#'*) ;;
*)
eval "$key=\"$value\""
export $key
esac
done < .data
$ . ./script.sh
$ . ./script.sh
Output:
输出:
$ echo $VAR1
abc
$ echo $VAR2
d#r3_P{os-!kblg1=mf6@3l^
but should be: d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^
但应该是: d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^
采纳答案by Inian
You don't need evalat all, just use declare
built-in in bash
to create variables on-the-fly!
您根本不需要eval,只需使用declare
内置的bash
来即时创建变量!
case "$key" in
'#'*) ;;
*)
declare $key=$value
export "$key"
esac
回答by Yedidia
Just escape the $ sign with backslash \
只需用反斜杠 \ 转义 $ 符号
回答by Rogus
If you cannot change the .datafile you have to escape the special character $
when assigning the value to key. Change the assignment line to:
如果您无法更改.data文件,则必须$
在将值分配给键时转义特殊字符。将分配行更改为:
eval "$key=\"${value//$/\$}\""
${variable//A/B}
means substituting every instance of A
to B
in variable
.
${variable//A/B}
意味着替换A
to B
in 的每个实例variable
。
More useful info on bash variables here
关于 bash 变量的更多有用信息在这里