首页 > 程序开发 > 软件开发 > 其他 >

Shell中判断字符串是否为空与单词分割

2014-08-20

前言Shell中通常用test命令判断文件类型和属性,以及数字、字符串的比较,[ expression ]是"test expression" 的同义词。注意:使用[ expression ]时应特别注意两端的空格!判断字符串是否为空Shell中判断

前言
Shell中通常用test命令判断文件类型和属性,以及数字、字符串的比较,[ expression ]是"test expression" 的同义词。
注意:使用[ expression ]时应特别注意两端的空格!
判断字符串是否为空
Shell中判断字符串是否为空通常有以下几种方法:
1. [ -n STRING ] : the length of STRING is nonzero
1 str=""
2 str1="hello"
3 [ -n "$str" ] && echo "No" || echo "Yes" # Yes
4 [ -n "$str1" ] && echo "No" || echo "Yes" # No
等价于:[ STRING ] : equivalent to −n STRING
1 str=""
2 str1="hello"
3 [ "$str" ] && echo "No" || echo "Yes" # Yes
4 [ "$str1" ] && echo "No" || echo "Yes" # No
2. [ -z STRING ] : the length of STRING is zero
1 str=""
2 str1="hello"
3 [ -z "$str" ] && echo "Yes" || echo "No" # Yes
4 [ -z "$str1" ] && echo "Yes" || echo "No" # No
3. 与空字符串比较:" = ", " == ", “ != ”
1 str=""
2 str1="hello"
3 [ "$str" = "" ] && echo "Yes" || echo "No" # Yes
4 [ "$str1" = "" ] && echo "Yes" || echo "No" # No
注:为了兼容旧的shell在进行空字符串判断可能出现问题,可用[ "x$s" = "x" ] 进行判断。
test或[]的使用注意事项
鸟哥在《鸟哥私房菜》里写了使用test或[ ]的注意事项:
(1)在[]内的每个组件都需要有空白键来分隔;
(2)在[]的变量,最好都以双引号括号起来;
(3)在[]内的常数,最好都以单或双引号括号起来。
注意第2条,如果给变量不加双引号会出现什么问题呢?
1 str=""
2 str1="hello"
3 [ -n $str ] && echo "No" || echo "Yes" # No
4 [ -n $str1 ] && echo "No" || echo "Yes" # No
第3行相当于:
test -n $str && echo "No" || echo "Yes" # No
会发现,不论字符串str是否为空,输出都为"No"!如果把 -n STRING放在[[]]里却又正常!这又是怎么回事呢?但是用[ -z STRING ]却不会出现同样的问题!
原来,在Bash Manual 的 test 内建函数中提到,当test命令有且仅有唯一一个不为空的参数时,总返回真值。这里唯一的参数是-n,所以总返回true!
复制代码
test and [ evaluate conditional expressions using a set of rules
based on the number of arguments.
0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
复制代码
但是如果用[[ -n $str ]]则判断正确,至于"[["的结果为何不同, 这是因为"[["是Bash特殊的语法结构,不是test命令。 而且,双中括号里面不会进行单词分割,所以参数替换后的空值依然还在,能正确测试!
复制代码
Ban Manual中:
[[ expression ]]
Return a status of 0 or 1 depending on the evaluation of the
conditional expression expression. Expressions are composed of
the primaries described below under CONDITIONAL EXPRESSIONS.
Word splitting and pathname expansion are not performed on the
words between the [[ and]]; tilde expansion,parameter and
variable expansion, arithmetic expansion, command substitution,
process substitution, and quote removal are performed.Condi-
tional operators such as -f must be unquoted to be recognized as
primaries.
复制代码
单词分割(Word-Splitting)
1 cmd="which who"
2 $cmd sh
3 # 执行结果:
4 /usr/bin/who
5 /bin/sh
若放到到引号里面,就不会进行单词分割,结果:
1 cmd="which who"
2 "$cmd" sh
3 -bash: which who: command not found
同样:在Bash中,“[[ ]]”里面的内容不会进行单词分割,而"[ ]"会。
相关文章
最新文章
热点推荐