Enhancing the (unofficial) bash strict mode

What’s about shell scripts?

I frequently write shell scripts for a variety of purposes. First, I like the flexibility and the vast number of tools that your average GNU/Linux shell provides; furthermore shell tools are very efficient and battle-hardened. For example, the implementation of regular expression matching in GNU’s awk or grep with respect to the standard one in programming languages like Python, Perl or Java leads to orders of magnitude of improvement in speed. If you can do it in the shell you can probably do it as fast as you could possibly do on a single machine and sometimes much faster than using Big Data platforms.

Tools for better scripts

Writing shell scripts can be very frustrating, though. For example, a bash script will happily continue if you mistype a variable, which at that point will have an empty value, and produce weird and unpredictable bugs.

So, do yourself a favor and make your life easier!

  1. use the (unofficial) bash strict mode by Aaron Maxwell. Here it is:

  2. install and start using Shellcheck, now. You can integrate it in a variety of editors (from vim to Sublime Text) and will warn you about more than 200 errors or deprecated constructs in your code.

Thanks to this combination my scripts are more predictable and robust, furthermore, I learned a lot about all the subtleties of the bash thanks to the very informative warnings of Shellcheck.

Sourcing vs Excuting

Using the bash strict mode can cause some problems if you are sourcing your scripts either in the shell or in other scripts because it will activate the “exit on error” option (set -e) that will cause your shell to exit on any command with a non-zero exit status.

The solution is adding a check to test wheter the script is being sourced or executed in a subshell:

in this way you can source your script in the shell or in another script without activating the strict mode by accident, it also allows you to test them by executing them directly. I have tested this method also with ZSH and it works as well.

The image is “Shell Scripted in Sand: Dark Contrast – An Apical Shot of Hard Rock Shell Scripted in Sand” by Kumar’s Edit on Flickr. Released under CC-BY 2.0.

Share on Facebook3Tweet about this on TwitterShare on Reddit0Buffer this pageFlattr the author