Linux shell if [ -n ] 正確使用方法


if [ str1 = str2 ]       當兩個串有相同內容、長度時為真 
if [ str1 != str2 ]      當串str1和str2不等時為真 
if [ -n str1 ]       當串的長度大於0時為真(串非空) 
if [ -z str1 ]        當串的長度為0時為真(空串) 
if [ str1 ]         當串str1為非空時為真

shell 中利用 -n 來判定字符串非空。

錯誤用法:

ARGS=$*

if [ -n $ARGS  ]

then

   print "with argument"

fi

print " without argument"

不管傳不傳參數,總會進入if里面。

原因:因為不加“”時該if語句等效於if [ -n ],shell 會把它當成if [ str1 ]來處理,-n自然不為空,所以為正。

 

正確用法:需要在$ARGS上加入雙引號,即"$ARGS".

 

ARGS=$*

if [ -n "$ARGS"  ]

then

   print "with argument"

fi

print " without argument"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM