shell 字符串

使用 -z:字符串长度位0时,为真;

使用 -n : 字符串长度不为0时,为真;

看八个示例,以及其执行结果

#! /bin/bash

mystr=""

if [ -n ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xxgg

 

#! /bin/bash

mystr=" "

if [ -n ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xx gg

 

#! /bin/bash

mystr=""

if [ -n "${mystr}" ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
ggxx

 

#! /bin/bash

mystr=" "

if [ -n “${mystr}” ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xx gg

 

#! /bin/bash

mystr=""

if [ -n ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xxgg

 

#! /bin/bash

mystr=" "

if [ -n ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xx gg

 

#! /bin/bash

mystr=""

if [ -z ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xxgg

 

#! /bin/bash

mystr=" "

if [ -z ${mystr} ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xx gg

 

#! /bin/bash

mystr=""

if [ -z "${mystr}" ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
xxgg

 

#! /bin/bash

mystr=" "

if [ -z "${mystr}" ]
then
     echo "xx"${mystr}"gg"
else
     echo "gg"${mystr}"xx"
fi


结果:
gg xx

 

 

判定字符串为空:http://stackoverflow.com/questions/13509508/check-if-string-is-neither-empty-not-space-in-shell-script


str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str"!=" " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2"!=" " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3"!=" " ]; then
        echo "Str3 is not null or space"
fi


# ./checkCond.sh 
Str is not null or space
Str2 is not null or space

You need a space on either side of the !=. Change your code to:

str="Hello World"
str2=" "
str3=""

if [ ! -z "$str" -a "$str" != " " ]; then
        echo "Str is not null or space"
fi

if [ ! -z "$str2" -a "$str2" != " " ]; then
        echo "Str2 is not null or space"
fi

if [ ! -z "$str3" -a "$str3" != " " ]; then
        echo "Str3 is not null or space"
fi

原因:

It's syntax. The first word on the command line is the command & subsequent ones are arguments. var=value [command [args]] is the syntax, in which a variable is assigned value.
For comparison, [ (/usr/bin/[) is the command & it requires var1, != & var2 to be 3 separate arguments. var1!=var2 is a single argument.

 

 

 

 

 

 

posted on 2014-07-14 18:24  阿加  阅读(181)  评论(0)    收藏  举报

导航