2

I work with a lot of shell scripts that use bash variables. So, for example, I might have a script like this:

option1="-blah_blah"
option2="-yada_yada"
option3="-whatever"
...
option99="-something_else"

./myCommand "$option1 $option12 $option97 $option45"

I am constantly editing that last command to run various engineering tests. The problem is, sometimes I misspell a variable. In that case, Bash simply substitutes an empty string, and my command does the wrong thing silently.

Is there a way to have Bash throw an exception when I try to use a variable that is not defined?

rlbond
  • 65,341
  • 56
  • 178
  • 228
  • Not sure how this could possibly be a duplicate of that question, as it still would not prevent an error if I misspelled a variable. – rlbond Feb 10 '15 at 19:07

1 Answers1

4

Use:

set -e # Stop on error. I can't believe that this is not default.

set -u # Stop if trying to use un-initialized variables.

MTilsted
  • 5,425
  • 9
  • 44
  • 76
  • 2
    `set -e` isn't as useful as you might like and can break in "interesting" ways so can't save you as much as you might want (and is sometimes actively not what you want). `set -u` is, likewise, somewhat annoying and not always as helpful as you would want (and sometime more exacting than you would like). Just for the record. – Etan Reisner Feb 04 '15 at 19:03
  • 1
    Read [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105), and you'll have a very good idea of why `set -e` is not default (beyond "making it default would break POSIX sh compatibility", which is reason enough). – Charles Duffy Dec 07 '16 at 15:36