【问题标题】:Split a string into key-value pairs and use them to set environment variables将字符串拆分为键值对并使用它们来设置环境变量
【发布时间】:2020-11-02 14:16:13
【问题描述】:

我有一个这样的字符串存储在一个环境变量中:

$ echo $PARAMS 
LOGGING=s3 ARGS="-foo bar -port 80" HELLO=world

我想拆分这个字符串并用它来设置独立的环境。 vars 这样我最终会得到:

$ env
LOGGING=s3
ARGS="-foo bar -port 80"
HELLO=world

我需要在 CI 系统的约束下执行此操作,因此理想情况下只需要一些 bash

【问题讨论】:

  • 不需要更改?
  • @PaulHodges 不确定您在暗示什么?我需要那些单独的环境。 vars set,它们当前未设置。
  • 是否可以轻松/可能将 $PARAMS 的值更改为逗号分隔,如 LOGGING=s3,ARGS="-foo bar -port 80",HELLO=world ?
  • @congbaoguier 是的,我可以将其更改为逗号分隔而不是空格分隔。你有使用 IFS 的想法吗?
  • 我的意思是,如果字符串格式正确,则不需要拆分字符串。如果在您当前的环境中执行,它们将在同一行上按原样工作,正如 Glenn 建议的 eval 或我建议的那样,写入文件并获取它。解析字符串很困难,因为其中一个变量嵌入了空格。它仍然可以完成,但更简单的解决方案比尝试实现语法更稳定。

标签: bash environment-variables


【解决方案1】:

你可以这样做:

$ eval "$PARAMS"
$ export $(grep -Po '\w+(?==)' <<< "$PARAMS")

然后

$ env | grep -e LOGGING -e ARGS -e HELLO
HELLO=world
ARGS=-foo bar -port 80
LOGGING=s3

这需要 GNU grep 来获取 -P

【讨论】:

  • 谢谢,这似乎有效。你能解释一下吗?我不确定我明白为什么 eval 在这里。
  • eval 在当前 shell 中将其参数作为代码执行。在 eval 之前,$PARAMS 只是一个包含字符的字符串。在 eval 之后,变量已在当前 shell 中声明,但不是(还)环境变量..
【解决方案2】:

我经常使用临时文件。

$: f=$(mktemp); echo "export $PARAMS">"$f"; . "$f"; echo "[$LOGGING] [$ARGS] [$HELLO]"; sh -c 'echo "$ARGS"'
[s3] [-foo bar -port 80] [world]
-foo bar -port 80

详细说明-

f=$(mktemp)                         # create a unique tempfile
echo "export $PARAMS" > "$f"        # write the declaration to the temp
. "$f"                              # source the tempfile into the current env, creating the vars
echo "[$LOGGING] [$ARGS] [$HELLO]"  # show that they are set
sh -c 'echo "$ARGS"'                # verify that they are exported

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多