shell中如何判斷一個(gè)變量是否為空
shell編程中,對(duì)參數(shù)的錯(cuò)誤檢查項(xiàng)中,包含了變量是否賦值(即一個(gè)變量是否為空),判斷變量為空方法如下:
1.變量通過(guò)" "引號(hào)引起來(lái)
#!/bin/sh
para1=
if [ ! -n "$para1" ]; then
echo "IS NULL"
else
echo "NOT NULL"
fi
【輸出結(jié)果】"IS NULL"
2.直接通過(guò)變量判斷
#!/bin/sh
para1=
if [ ! $para1 ]; then
echo "IS NULL"
else
echo "NOT NULL"
fi
【輸出結(jié)果】"IS NULL"
3.使用test判斷
#!/bin/sh
dmin=
if test -z "$dmin"
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
【輸出結(jié)果】"dmin is not set!"
4.使用""判斷
#!/bin/sh
dmin=
if [ "$dmin" = "" ]
then
echo "dmin is not set!"
else
echo "dmin is set !"
fi
【輸出結(jié)果】"dmin is not set!"