英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论