[英]How to set multiple environment variables from output of other command in bash?
我设置了一个包含多个值的变量。 (这是我从heroku config --shell
得到的,已编辑)
保存命令 output 的命令是
envvars=`heroku config --shell -a heroku-app`
echo "$envvars"
结果是这样的:
BH_SERVER=000000000000000000
DATABASE_URL='postgres://stringno1:randomstring1@someserver.com:5432/randomstring2'
DISCORD_TOKEN=some.veryveryveryvery.long.token.string
EXM_SERVER=000000000000000001
MUTED_SERVER='000000000000000002, 000000000000000003'
SUPER_USER='000000000000000004, 000000000000000005'
TEST_SERVER=000000000000000006
TZ=Asia/Seoul
现在我想将这些值设置为环境变量。 这些不能是永久性的,因为这些只需要 python 应用程序,稍后将在脚本中执行。 我想我可以使用=
作为分隔键和值的分隔符,但不能 100% 确定这一点。 (不知道 heroku convar 效果如何)
我希望这些像 output。
echo $BH_SERVER
# 000000000000000000
echo $DATABASE_URL
# postgres://stringno1:randomstring1@someserver.com:5432/randomstring2
# Note that there is no ' in start and end of line
echo $DISCORD_TOKEN
# some.veryveryveryvery.long.token.string
# Note that . is still there.
echo $MUTED_SERVER
# 000000000000000002, 000000000000000003
# Even if there is space in string, it should be treated as one line
# Also, there is no ' in start and end of line
echo $TZ
# Asia/Seoul
# / is not interpreted. I think this is normal.
有一些已经回答的问题,但我没有找到任何符合我条件的答案。
我放了git-bash
标签,因为我正在研究 Git Bash 但我认为这个问题的解决方案与 Bash 相同。
您可以使用eval
。 确保使用双引号,否则带有空格和引号的设置将被破坏。
eval "$envvars"
或者
eval "$(heroku config --shell -a heroku-app)"
您可以使用子shell 来隔离对一段代码的更改。
# Parentheses create a subshell, or child process.
# Variables set in a child process don't affect the parent.
(
eval "$(heroku config --shell -a heroku-app)"
echo "$BH_SERVER"
echo "$DATABASE_URL"
echo "$DISCORD_TOKEN"
echo "$MUTED_SERVER"
echo "$TZ"
)
# The variables will be unset here.
您可以将 echo output 添加到临时文件中,获取文件,然后删除临时文件:
echo $envvars > /tmp/tmp.env && source /tmp/tmp.env && rm /tmp/tmp.env
如果在 gitbash /tmp 上不可用,请使用另一个可用路径来创建临时文件
或者,您可以使用以下不需要临时文件的格式
echo $envvars | source /dev/stdin
我不确定,但这应该可以
eval $(echo $envvars) ./script.sh
或者
eval $(echo $envvars) python script.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.