bash bash中未设置和空变量之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5406858/
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
difference between unset and empty variables in bash
提问by green69
Using bash, what's the best method to check if a variable is empty or not?
使用 bash,检查变量是否为空的最佳方法是什么?
If I use:
如果我使用:
if [ -z "$VAR" ]
as suggested in a forum this works for an unset variable but it is true when the variable is set but empty. Suggestions?
正如在论坛中所建议的,这适用于未设置的变量,但当变量已设置但为空时确实如此。建议?
采纳答案by Kevin Beck
if [ `set | grep '^VAR=$'` ]
This searches for the string "VAR=" in the list of variables set.
这将在变量集列表中搜索字符串“VAR=”。
回答by geekosaur
${var+set}substitutes nothing if the variable is unset and setif it is set to anything including the empty string. ${var:+set}substitutes setonly if the variable is set to a non-empty string. You can use this to test for either case:
${var+set}如果变量未设置并且set设置为包括空字符串在内的任何内容,则不替换任何内容。 仅当变量设置为非空字符串时才${var:+set}替换set。您可以使用它来测试任何一种情况:
if [ "${foo+set}" = set ]; then
# set, but may be empty
fi
if [ "${foo:+set}" = set ]; then
# set and nonempty
fi
if [ "${foo-unset}" = unset ]; then
# foo not set or foo contains the actual string 'unset'
# to avoid a potential false condition in the latter case,
# use [ "${foo+set}" != set ] instead
fi
if [ "${foo:-unset}" = unset ]; then
# foo not set or foo empty or foo contains the actual string 'unset'
fi
回答by mug896
You can test with
你可以测试
[ -v name ]
[ -v name ]
name is without $sign
名字没有$符号
回答by user3067510
This would be true only for empty, not unset (or has value)
这仅适用于空,而不是未设置(或具有值)
[ -z ${VAR-X}
回答by kurumi
well, here's one way
嗯,这是一种方法
$ s=""
$ declare -p s
declare -- s=""
$ unset s
$ declare -p s
bash: declare: s: not found
an error message will occur if the variable is unset.
如果未设置变量,则会出现错误消息。

