天天看點

linux shell 中判斷字元串為空的正确方法

help指令可以檢視幫助

help test

正确做法:

#!/bin/sh

STRING=

if [ -z "$STRING" ]; then

    echo "STRING is empty"

fi

if [ -n "$STRING" ]; then

    echo "STRING is not empty"

fi

[email protected]:~# ./zerostring.sh

STRING is empty

-------------------------------------------------------------------------

錯誤做法:

#!/bin/sh

STRING=

if [ -z $STRING ]; then

    echo "STRING is empty"

fi

if [ -n $STRING ]; then

    echo "STRING is not empty"

fi 

輸出錯誤結果:

[email protected]:~# ./zerostring.sh

STRING is empty

STRING is not empty

繼續閱讀