1. Use a portable shebang

Use:

instead of

The reason for: on some systems bash can have various locations Eg.: /sbin/bash , /usr/local/bin/bash , /usr/bin/bash

Note: This applies for other scripting languages as well, not only for bash .


2. Perform “Sanity Checks”

Sanity checks are run-time tests  that protect the script from running in unsuitable environments . So before running the actual code of your script, do some checks to assure that nothing unexpected will happen . Don’t forget to include meaningful error messages if one of the sanity checks fails.

The most common checks performed in bash scripts are :

2.1 Test if the script is being run by the desired user

Eg.:

2.2 Test if you have read / write access in certain locations

2.3 Test if the programs are in $PATH

If you are planning to use an “exotic command”, don’t forget to test its existence first (in this way you can safely rely on it):


3. Clean up after yourself

It’s a very common for bash scripts to write data in temporary files . Sometimes those temporary files can become rather large (or numerous), so we will considered a lack of respect “forgetting” to remove them . Let’s take a look at the following code:

By using trap we will be able to trigger our cleanup function when certain conditions are met .


4. Make good use of stdout and stderr .

It’s always a sign of good taste, to echo informational messages to stdout and errors to stderr .


5. Use “$var” (double quotes) when working with file variables .

In bash file names are dangerous strings that contain all kinds of “dangerous characters” like spaces, newlines or tabs .

Example:

Let’s create a file called: “a file with spaces”:

Now let’s keep this filename in a bash variable called $var1:

If we use the variable name without quotes and we try to test the file existence, we will encounter errors:

So the right approach to avoid those kind of issues if tho use the double quotes:

Why was the error produced in the first place ? Beacause “[” is actually a program that expects a predefined number of arguments . Because of the spaces (in the first example) “[” was actually receiving more arguments than was expecting .


5. Choose your returning codes wisely .

If you want to know more about this issue, please take a look to this article: Please, don’t use exit(-1) by Renato Cunha .


Other things you might want to take in consideration

  • Include your name, the creation date, and some form of contact info (forum, irc, etc.) ;
  • Describe when and how is your script supposed to be used ;
  • Don’t give your script a cryptic name . Come with something descriptive . If you cannot find anything descriptive enough, at least come with something nice or funny ;
  • Don’t forget to add use the .sh suffix – otherwise things can get pretty confusing and the user will have to open up the file to see what kind of script he’s using .

If you have something to add please don’t hesitate to comment !
I consider this article to be still work in progress .

5 thoughts on “Bash Scripting – Best Practices

  1. Writing readable, scalable and maintainable English sentences can be a daunting task, but it’s definitively possible.

    Most importantly: don’t put a space between the last word of the sentence and the punctuation. This is silly and may cause problems on some setups. I’m running a 22 year old machine with faulty short-term memory and a relatively recent installation of an English locale and this thing causes a considerable lag when parsing your text.

    Reply
  2. Thanks for you kind feedback Dear Robot, unfortunately the art of writing maintainable English sentences is still a mystery for me.

    PS: Should I change the captcha plugin ? Was it to easy for you ?

    Reply
  3. I always test my commands in a loop with $ while [ 1 ]; do time cmd; sleep 0.5s; done to and compare it to other alternative . You’ll be surprised of some results… I hardly ever use ${#FOO} to get the length of a string anymore, I always user $ echo -n "$FOO" | wc -c, which tunrns out is up to x3 faster. And The same with $ myCmd <<< "$FOO", takes twice as long to run as $ echo -n "$FOO" | myMcd.

    Reply
  4. Pingback: best practice | Kevin's Blog

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url=""> 

required

Are we human, or are we dancer *