[lang-ref] Null coalescing ( bash )
@test "null coalescing" {
# x="${a:-not set}"
# Use default if unset or empty.
unset a
x="${a:-not set}"
[ "$x" == "not set" ]
a=""
x="${a:-not set}"
[ "$x" == "not set" ]
a="test"
x="${a:-not set}"
[ "$x" = "test" ]
}
@test "null coalescing alternative 1" {
# x="${a-not set}"
# Use default only if unset (empty counts as set).
unset a
x="${a-not set}"
[ "$x" == "not set" ]
a=""
x="${a-not set}"
[ "$x" == "" ]
a="test"
x="${a-not set}"
[ "$x" = "test" ]
}
@test "null coalescing alternative 2" {
# : "${x:=not set}"
# If unset or empty, assign default to x (and expand to that value).
# this is used for initialize value
unset x
: "${x:=not set}"
[ "$x" = "not set" ]
x=""
: "${x:=not set}"
[ "$x" = "not set" ]
x="test"
: "${x:=not set}"
[ "$x" = "test" ]
}