2

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.

Daan
  • 1,417
  • 5
  • 25
  • 40
  • Does this answer your question? [How can I make bash treat undefined variables as errors?](https://stackoverflow.com/questions/41020844/how-can-i-make-bash-treat-undefined-variables-as-errors) – Enlico Mar 07 '20 at 23:54
  • @enrico Kinda. But, although it makes clear that using undefined variables won't throw any errors, it doesn't explicitly state that doing so is good or proper. It could still be bad to use undefined variables even if there are no errors. I wouldn't feel confident enough unless I asked the question directly. – Daan Mar 08 '20 at 10:36
  • Whether using an undefined variable is good or proper is opinion-based (in my opinion, ahahah). Evidence supporting what I'm saying, is that `bash` offers `${parameter:-word}` as well as `${parameter-word}`, `${parameter:=word}` as well as `${parameter=word}`, and so on, where the use of the colon makes `bash` check for `parameter` null-ness or unset-ness, whereas its absence makes it check only for unset-ness. – Enlico Mar 08 '20 at 13:12
  • 1
    Note that the variable is not guaranteed to be unset in this case. It could easily have a junk value inherited from the user's shell. It's better to explicitly set or unset it – that other guy Mar 08 '20 at 17:06

1 Answers1

1

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 2
    There's also `${foo:?Error message here}`, which forces an error if the variable is undefined, even without `set -u`. BTW, I always recommend double-quoting variable references (e.g. `echo "$foo"` instead of `echo $foo`), to avoid a variety of weird potential problems with how the shell treats unquoted variable references. – Gordon Davisson Mar 08 '20 at 05:47
  • Gordon You're right, thanks. I didn't quote vars since this is just POC code – oguz ismail Mar 08 '20 at 06:08