2012-11-22 32 views
45

我想運行下面的shell腳本,它應該檢查一個字符串既不是空格也不是空格。但是,我得到的所有3個字符串的輸出都是相同的。我曾嘗試使用「[[」語法,但無濟於事。檢查字符串既不是空也不在shell腳本中的空格

這裏是我的代碼:

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 

回答

76

您需要在!=的兩側留出空間。你的代碼更改爲:

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 
+0

非常感謝,它的工作原理。但是我想知道爲什麼這個任務不使用空間,而是進行比較。 –

+5

^^這是語法。命令行中的第一個單詞是命令,後面的單詞是參數。 'var = value [command [args]]'是語法,其中一個變量被賦值。作爲比較,'['('/ usr/bin/[')是命令&它需要var1,!=&var2是3個獨立的參數。 var1!= var2是一個參數。 – anishsane

+0

@anishsane非常感謝細節,我現在得到它=) –

40

對於外殼檢查空字符串

if [ "$str" == "" ];then 
    echo NULL 
fi 

OR

if [ ! "$str" ];then 
    echo NULL 
fi 
+4

shell的字符串相等操作符是'='。 '=='是shell編程人員發明的一種不可移植的黑客技術,它可以混淆年輕程序員的思想。 – Jens

6

要檢查是否字符串爲空或包含只有空白,你可以使用:

shopt -s extglob # more powerful pattern matching 

if [ -n "${str##+([[:space:]])}" ]; then 
    echo '$str is not null or space' 
fi 

Shell Parameter ExpansionPattern Matching Bash的手冊中的

+1

你能解釋這一點爲學習目的?這看起來像亂碼^^;這是像grep還是什麼? –

+1

@Keith M:查看我在帖子中提供的文檔的鏈接。 –

11

如果您需要檢查針對空白任何金額,而不僅僅是單一的空間,你可以這樣做:

要去除的多餘的空白字符串(也condences中間空格一個空格):

trimmed=`echo -- $original` 

--確保如果$original包含回聲瞭解交換機,他們仍然被視爲要呼應普通參數。此外,不要將""圍繞$original,否則空間不會被刪除。

之後,您可以檢查$trimmed是否爲空。

[ -z "$trimmed" ] && echo "empty!" 
+0

在bourne shell中,我以「 - 」作爲修剪的值。 –

2

另一個快速測試字符串的東西,但空間。

if [[ ! -z "${str/ //}" ]]; then 
    echo "It is not empty!" 
fi 
1
[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty" 

剝從字符串所有新行和空格都將導致一個空白的將減少到什麼可以測試並採取行動

相關問題