访问未映射到有效Shell变量名称的环境变量 [英] Accessing environment variables that don't map to valid shell variable names

查看:86
本文介绍了访问未映射到有效Shell变量名称的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何(尽可能多地)合理且可移植地处理名称不映射到有效shell变量的环境变量.结果必须逐字节准确是至关重要的,因此我不愿意经历诸如解析env工具的输出之类的黑客攻击.

I'm trying to figure out how to sanely and portably (as much as possible) deal with environment variables with names that don't map to valid shell variables. It is critical that results be byte-for-byte accurate, so I'm unwilling to go through hacks such as parsing the output of the env tool.

env 'Invalid Name=Some Value' bash <<'EOF'
s='Invalid Name'
printf '%q\n' "${!s}"
EOF

我希望上面的代码会发出Some Value;但是,它返回一个空字符串.

I would hope that the above code would emit Some Value; instead, however, it returns an empty string.

推荐答案

一种不可移植的方法(仅Linux)是解析/proc/self/environ:

One unportable approach (Linux-only) is to parse /proc/self/environ:

declare -A environ
while IFS='' read -r -d ''; do
  var=${REPLY%%=*}
  val=${REPLY#*=}
  environ[$var]="$val"
done </proc/self/environ
printf '%q\n' "${environ["Invalid Name"]}"

这篇关于访问未映射到有效Shell变量名称的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆