檢查 Bash 中的變數是否為空
-
使用
-z選項檢查 Bash 中的變數是否為空 -
在 Bash 中使用
-n選項來檢查變數是否為空 - 檢查 Bash 中的變數是否為空 - 與空字串比較
- 檢查 Bash 中的變數是否為空 - 使用替換方法檢查
本教程說明了使用帶有 -z 和 -n 選項的 test 命令在 bash 中檢查變數是否為空。
使用 -z 選項檢查 Bash 中的變數是否為空
我們使用帶有 -z 選項的 test 命令。 -z 選項檢查字串變數的長度是否為 0。
如果字串變數的長度為 0,則測試返回 true,並且指令碼將字串變數為空輸出到標準輸出。如果字串變數的長度不是 0,指令碼會列印出字串變數不為空。
在下面的例子中,greet 變數有一個分配給它的字串。在測試過程中,檢查 greet 變數儲存的字串值的長度是否為 0。
由於 greet 變數有字串 Hi,它分配了兩個字元,測試返回 false,並且指令碼在標準輸出中列印 greet 變數不為空。
greet='Hi'
if [ -z "$greet" ]
then
echo "\$greet is empty"
else
echo "\$greet is not empty"
fi
輸出:
$greet is not empty
greet 變數在下面的指令碼中被分配給一個空字串。使用 test/[ 命令檢查 greet 變數以檢視其字串值的長度是否為 0。
由於 greet 變數被分配給一個空字串,測試返回 true,並且指令碼列印到標準輸出 greet 變數為空。
#!/bin/bash
greet=''
if [ -z "$greet" ]
then
echo "\$greet is empty"
else
echo "\$greet is not empty"
fi
輸出:
$greet is empty
在 Bash 中使用 -n 選項來檢查變數是否為空
下面的指令碼使用帶有 -n 選項的 test 命令來檢查字串變數是否為空。 -n 選項檢查字串變數中值的長度是否為非零。
如果變數中字串的長度不為零,則測試返回 true,並列印出該變數不為空。如果字串變數的長度為零,則測試返回 false,並列印出該變數為空。
greet 變數在下面的指令碼中被分配給一個空字串。當使用 test 命令檢查 greet 變數時,如果它儲存的字串的長度不為零,則返回 false,並且指令碼執行 else 部分中的命令。
#!/bin/bash
greet=''
if [ -n "$greet" ]
then
echo "\$greet is not empty"
else
echo "\$greet is empty"
fi
輸出:
$greet is empty
greet 變數已分配給 Hi,這是一個在下面的指令碼中包含兩個字元的字串。
檢查 greet 變數中的字串長度是否為非零的測試返回 true,因為 greet 變數被分配給具有兩個字元的字串。該指令碼在標準輸出中列印出 greet 變數不為空。
#!/bin/bash
greet='Hi'
if [ -n "$greet" ]
then
echo "\$greet is not empty"
else
echo "\$greet is empty"
fi
輸出:
$greet is not empty
檢查 Bash 中的變數是否為空 - 與空字串比較
我們可以通過將其與""進行比較來檢查該值是否為空。
x="Non-empty variable"
if [[ "$x" == "" ]]; then
echo "x is empty"
else
echo "x is not empty"
fi

檢查 Bash 中的變數是否為空 - 使用替換方法檢查
如果定義了 x,則表示式被替換為 test,否則為 null。
if [ ${x:+test} ]; then
echo "x is not empty"
else
echo "x is empty"
fi

