分页: 1 / 1
[问题]关于参数-n的一个小问题
发表于 : 2008-05-31 21:31
由 sihaiwuya1986
请教下面的代码
if [ -n $var ];then
echo "not empty"
else
echo "empty"
fi
var变量我并没有赋值,将其保存为test.然后执行sh -x test,终端显示如下:
+ '[' -n ']'
+ echo 'not empty'
not empty
我很纳闷,明明是空,可为什么却说不是空呢?请教各位高手。
发表于 : 2008-05-31 21:49
由 alinmn
if [ -n "$var" ]
要加引号
[已解决]谢谢alinmn.搞定了
发表于 : 2008-05-31 21:58
由 sihaiwuya1986
搞定了。呵呵。多谢
[问题]再问个问题
发表于 : 2008-05-31 22:05
由 sihaiwuya1986
#!/bin/sh
help()
{
cat < This is a generic command line parser demo.
USAGE EXAMPLE: cmdparser -l hello -f -- -somefile1 somefile2
HELP
exit 0
}
while [ -n "$1" ]; do
case $1 in
-h) help;shift 1;; # function help is called
-f) opt_f=1;shift 1;; # variable opt_f is set
-l) opt_l=$2;shift 2;; # -l takes an argument -> shift by 2
--) shift;break;; # end of options
-*) echo "error: no such option $1. -h for help";exit 1;;
*) break;;
esac
done
echo "opt_f is $opt_f"
echo "opt_l is $opt_l"
echo "first arg is $1"
echo "2nd arg is $2"
以上代码适从本论坛的shell编程基础里面copy的,可是执行sh -x cmdparser -h后,却成了个死循环,屏幕不断提示如下:
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
+ '[' -n -h ']'
+ case $1 in
这是怎么回事。好像并没有执行case的判断后的语句,可我看不出有什么错误?