如何从 bash 中其他命令的输出设置多个环境变量?

How to set multiple environment variables from output of other command in bash?

我设置了一个包含多个值的变量。 (这是我从 heroku config --shell 得到的,已编辑)
保存命令输出的命令是

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怎么用的好)

我期待类似的输出。

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 $(echo $envvars) ./script.sh

eval $(echo $envvars) python script.py

您可以将 echo 输出添加到临时文件,获取文件然后删除临时文件 :

echo $envvars > /tmp/tmp.env && source /tmp/tmp.env && rm /tmp/tmp.env

如果在 gitbash 上 /tmp 不可用,请使用另一个可用路径来创建临时文件

或者您可以使用以下不需要临时文件的格式

echo $envvars | source /dev/stdin

您可以使用 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.