Proper to use unassigned variable?

Viewed 203

I was wondering if it is proper in Bash to, say, print a possibly unassigned string:

if [[ test ]]; then
  str="foo"
fi

printf "foo or empty: %s" "$str"

Or do I have to assign a default value outside of the if-statement like str=""

I don't get any errors so it seems to be fine.

1 Answers

It is fine unless -u option is set.

$ unset foo
$ echo $foo

$ set -u
$ echo $foo
bash: foo: unbound variable
$

Some assign a default value as you mentioned, and some reference them like ${foo-} to avoid that error.

Related