检查环境变量是否已设置的可移植方法

huangapple go评论45阅读模式
英文:

Portable way to check if an environment variable is set

问题

在Bash中,您可以使用test -v FOO来检查环境变量是否已设置。但在Debian 11上的Dash中,这种方法不起作用,因为它的test不支持-v选项:

# test -v FOO
dash: 2: test: -v: unexpected operator

是否有一种可移植的方法,可以在Bash和Dash中(最好在更多的shell中也能)使用?

英文:

In Bash you can check if an environment variable is set with test -v FOO. It doesn't work in Dash on Debian 11 though because its test doesn't support -v:

# test -v FOO
dash: 2: test: -v: unexpected operator

Is there a portable way that works in Bash and Dash (and ideally more shells, but those are the main ones I am concerned with)?

答案1

得分: 2

你可以在变量的展开中使用 +,并测试它:

test "${FOO+x}"

如果 FOO 未设置,展开结果为空字符串,否则为 x

英文:

You can use + in the expansion of the variable, and test it:

test "${FOO+x}"

The expansion results in an empty string if FOO is unset, or x otherwise.

huangapple
  • 本文由 发表于 2023年7月31日 22:21:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76804527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定