除此之外,Bash 還有提供一些好用的參數擴展(Parameter Expansion)如下。
參數為 unset 表示參數還沒有被初始化,為 null 表示參數被初始化為空字串,
例如:var0=
使用 unset 指令可以將參數變成 unset
1. 參數為 unset 或 null 時的參數擴展(Parameter Expansion)
a. ${parameter:-word}
當 parameter 為 unset 或 null 時,擴展為 word。省略冒號( : ),
如 ${parameter-word} 則只有檢查 parameter 是否為 unset。
範例:
#!/bin/sh
echo "var0 is unset"
unset var0
echo \${var0:-value0} = ${var0:-value0}
echo ""
echo "var0 is null"
var0=
echo \${var0:-value1} = ${var0:-value1}
echo ""
echo "var0 is set to default"
var0=default
echo \${var0:-value2} = ${var0:-value2}
結果:
${var0:-value0} = value0
var0 is null
${var0:-value1} = value1
var0 is set to default
${var0:-value2} = default
b. ${parameter:=word}
當 parameter 為 unset 或 null 時,擴展為 word,且 word 被設定給
parameter,省略冒號( : ),如 ${parameter=word} 則只有檢查 parameter
是否為 unset。
範例:
#!/bin/sh
echo "var0 is unset"
unset var0
echo \${var0:=value0} = ${var0:=value0}
echo \${var0} = ${var0}
echo ""
echo "var0 is null"
var0=
echo \${var0:=value1} = ${var0:=value1}
echo \${var0} = ${var0}
echo ""
echo "var0 is set to default"
var0=default
echo \${var0:=value2} = ${var0:=value2}
var0 is unset
${var0:=value0} = value0
${var0} = value0
var0 is null
${var0:=value1} = value1
${var0} = value1
var0 is set to default
${var0:=value2} = default
${var0} = default
c. ${parameter:?word}#!/bin/sh
echo "var0 is unset"
unset var0
echo \${var0:=value0} = ${var0:=value0}
echo \${var0} = ${var0}
echo ""
echo "var0 is null"
var0=
echo \${var0:=value1} = ${var0:=value1}
echo \${var0} = ${var0}
echo ""
echo "var0 is set to default"
var0=default
echo \${var0:=value2} = ${var0:=value2}
echo \${var0} = ${var0}
結果:
${var0:=value0} = value0
${var0} = value0
var0 is null
${var0:=value1} = value1
${var0} = value1
var0 is set to default
${var0:=value2} = default
${var0} = default
當 parameter 為 unset 或 null 時,word 會輸出到標準錯誤輸出 (stderr),
省略冒號( : ),如 ${parameter?word} 則只有檢查 parameter 是否為
unset。
範例:
#!/bin/sh
echo "var0 is unset"
unset var0
echo \${var0:?var0 is unset or null} = ${var0:?var0 is unset or null}
echo ""
結果:
var0 is unset
./expansion.sh: 5: var0: var0 is unset or null
./expansion.sh: 5: var0: var0 is unset or null
範例:
#!/bin/sh
#!/bin/sh
echo "var0 is null"
var0=
echo \${var0:?var0 is unset or null} = ${var0:?var0 is unset or null}
echo ""
結果:
var0 is null
./expansion.sh: 5: var0: var0 is unset or null
#!/bin/sh
echo "var0 is set to default"
var0=default
echo \${var0:?var0 is unset or null} = ${var0:?var0 is unset or null}
結果:
var0 is set to default
${var0:?var0 is unset or null} = default
d. ${parameter:+word}
當 parameter 不是 unset 或 null 時,擴展為 word,省略冒號( : ),
如 ${parameter+word} 則只有檢查 parameter 是否為 unset。
範例:
#!/bin/sh
echo "var0 is unset"
unset var0
echo \${var0:+value0} = ${var0:+value0}
echo ""
echo "var0 is null"
var0=
echo \${var0:+value1} = ${var0:+value1}
echo ""
echo "var0 is set to default"
var0=default
echo \${var0:+value2} = ${var0:+value2}
結果:
${var0:+value0} =
var0 is null
${var0:+value1} =
var0 is set to default
${var0:+value2} = value2
沒有留言:
張貼留言