bash 如何遍历所有打印键和值的 ENV 变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39529648/
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
How to iterate through all the ENV variables printing key and value?
提问by Gajus
I'd like to iterate through the variables in env
printing:
我想遍历env
打印中的变量:
name: ${name} value: ${value}
Simply splitting by line break and iterating does not work, because of multi-line values, e.g.
由于多行值,例如,简单地按换行符和迭代拆分是行不通的
SERVER_TLS_SERVER_CRT=-----BEGIN CERTIFICATE-----
foo
-----END CERTIFICATE-----
The use case is to workaround Docker limitationthat restricts passing multi-line variables via --env-file
.
用例是解决Docker 限制,该限制限制通过--env-file
.
采纳答案by geirha
Here's the solution from #bash.
这是#bash 的解决方案。
unset IFS
args=() i=0
for var in $(compgen -e); do
printf -v 'args[i++]' -e%s=%s "$var" "${!var}"
done
I initially thought the idea was to output, hence printf %q was necessary, but that's not the case when just building an arguments array, so it can be simplified to this:
我最初认为这个想法是输出,因此 printf %q 是必要的,但在构建参数数组时并非如此,因此可以简化为:
unset IFS
args=()
for var in $(compgen -e); do
args+=( "-e$var=${!var}" )
done
回答by anubhava
You can use env -0
to get a null terminated list of name=value
pairs and use a for loop to iterate:
您可以使用env -0
以获取空终止的name=value
对列表并使用 for 循环进行迭代:
while IFS='=' read -r -d '' n v; do
printf "'%s'='%s'\n" "$n" "$v"
done < <(env -0)
Above script use process substitution, which is a BASH feature. On older shells you can use a pipeline:
上面的脚本使用了进程替换,这是一个 BASH 特性。在较旧的 shell 上,您可以使用管道:
env -0 | while IFS='=' read -r -d '' n v; do
printf "'%s'='%s'\n" "$n" "$v"
done