2017年12月29日 星期五

Bash Shell | 如何使用參數擴展 Parameter Expansion

最基本的參數擴展(Parameter Expansion),以 $ 字號開頭,後面接參數名,例如:${parameter},大括號 ( { ) 可以加或不加,例如:$parameter,但是如果遇到參數名與其後面的字元連接,在參數擴展時會產生問題,因此要加上大括號 ( { ) 來做區隔。
除此之外,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 is unset
${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}
echo \${var0} = ${var0}

結果:

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}
   當 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

範例:

#!/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 is unset
${var0:+value0} =

var0 is null
${var0:+value1} =

var0 is set to default
${var0:+value2} = value2

沒有留言:

張貼留言