在 Bash 中分配預設值
Aashish Sunuwar
2022年5月11日
Bash
Bash Variable
本文將介紹用於為 bash 指令碼中的變數提供預設值的方法。
為 Bash 指令碼中的變數提供預設值
我們在 bash 指令碼中提供預設值時遵循的基本方法如下。
variable={$variable:-value}
但是我們可以通過在開頭使用冒號來使用更好的簡寫形式。
: ${variable:=value}
開頭的冒號忽略了引數。
使用 ${variable-value} 或 ${variable:-value}
echo ${greet-hello}
echo ${greet:-hello}
greet=
echo ${greet-hello}
echo ${greet:-hello}
輸出:
hello
hello
hello
使用 ${greet-hello} 和 ${greet:-hello} 之間的主要區別在於,如果從未設定變數 greet,${greet-hello} 將使用預設值 hello 為一個值。另一方面,如果變數從未設定值或設定為 null 即 greet= ,${greet:-hello} 將使用預設值。
使用 ${variable:-value} 或 ${variable:=value}
echo ${greet:-Hello}
echo ${greet:-Namaste}
echo ${greet:=Bonjour}
echo ${greet:=Halo}
輸出:
Hello
Namaste
Bonjour
Bonjour
使用:- 會將變數替換為預設值,而:= 會將預設值分配給變數。
在給定的示例中,
${greet:-Namaste}列印出Namaste因為${greet:-Hello}已將greet變數替換為預設值,因為它沒有設定。${greet:=Bonjour}會將greet的值設定為Bonjour,因為它的值從未設定過。${greet:=Halo}不會使用預設值Halo,因為變數greet是先前設定的值,即Bonjour。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe