什么时候要给变量引用加双引号

sh/bash/dash/ksh/zsh等Shell脚本
回复
hugebrush
帖子: 94
注册时间: 2008-03-05 21:58

什么时候要给变量引用加双引号

#1

帖子 hugebrush » 2008-05-12 23:22

发现下面代码的运行结果是:
abc is not empty
abc is empty

代码: 全选

abc=
[ -n $abc ] && "abc is not empty"
[ -z $abc ] && "abc is temp"
后来给$abc加引号后结果正常:

代码: 全选

[ -n “$abc“ ] && "abc is not empty"
[ -z “$abc“ ] && "abc is temp"
什么时候应该给变量引用加双引号?
头像
laborer
帖子: 1016
注册时间: 2005-10-25 11:15
联系:

#2

帖子 laborer » 2008-05-13 11:47

因为$abc是空,如果这里不加双引号,那么
[ -n $abc ] 等价于 [ -n ]
没有参数时,这句总返回为真。
hreiser@oakland:~$ killall -9 wife
police@oakland:~$ sudo find / -user hreiser
court@oakland:~$ sudo mv /home/hreiser /jail/
court@oakland:~$ sudo usermod -d /jail/hreiser -s "/usr/sbin/chroot /jail/" hreiser
hugebrush
帖子: 94
注册时间: 2008-03-05 21:58

#3

帖子 hugebrush » 2008-05-14 14:54

Thanks.
回复