質問

When using the ${parameter:-word} form of parameter expansion to evaluate to a default value if the variable is unset, what is the best practice for quotes?

For example, assume a Bash shell script with -u set (to generate an error when an undefined or unset variable is evaluated), to test if a variable has a value, what would be the best way to write the equivalent of if [[ -z "$FOO" ]]?

if [[ -z "${FOO:-}" ]]

or

if [[ -z ${FOO:-""} ]]

or something else?

役に立ちましたか?

解決

If you are using the latest version of bash (4.2 as of this writing), you can use the -v option to test if a variable is set without trying to expand it at all.

if [[ -v FOO ]]; then
    echo "FOO=$FOO"
else
    echo "FOO not set"
fi

If you are using an older version, I would just use

if [[ -z ${FOO:-} ]];

The quotes aren't necessary, and IMO this looks cleanest.

他のヒント

I like to do it like this

if (( ! ${#FOO} ))

Example

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top