shell判斷乙個變數是否為空

2022-05-05 07:42:10 字數 897 閱讀 3897

1.最直接簡單的判斷

[ ! $a ] && echo "a is null"
不用那些if語句了,直接縮短**量。

2. 變數通過" "引號引起來

如下所示:,可以得到結果為 is null.

#!/bin/sh 

a= if [ ! -n "$a" ]; then

echo "is null"

else

echo "not null"

fi

3. 直接通過變數判斷

如下所示:得到的結果為: is null,跟第一種方法一樣的,只是**長一點,推薦使用第一種判斷方式,簡單明瞭。

#!/bin/sh 

a= if [ ! $a ]; then

echo "is null"

else

echo "not null"

fi

4. 使用test判斷

得到的結果就是: a is not set!

#!/bin/sh 

a= if test -z "$a" then

echo "a is not set!"

else

echo "a is set !"

fi

5. 使用""判斷

#!/bin/sh 

a= if [ "$a" = "" ]; then

echo "a is not set!"

else

echo "a is set !"

fi

這種情況下容易讓腳本報錯

shell中if判斷乙個變數為空

1.最直接簡單的判斷 a echo a is null 不用那些if語句了,直接縮短 量。2.變數通過 引號引起來 如下所示 可以得到結果為 is null.bin sh a if n a then echo is null else echo not null fi3.直接通過變數判斷 如下所示 ...

在shell中如何判斷乙個變數是否為空

在shell中如何判斷乙個變數是否為空 判斷乙個指令碼中的變數是否為空,我寫了乙個這樣的shell指令碼 bin sh filename test.sh para1 if n para1 then echo is null else echo not null fi 然後把該指令碼 test.sh通...

在shell中如何判斷乙個變數是否為空

在shell中如何判斷乙個變數是否為空 判斷乙個指令碼中的變數是否為空,我寫了乙個這樣的shell指令碼 c bin sh filename test.sh para1 if n para1 then echo is null else echo not null fi 然後把該指令碼 test.s...