Skip to content
SumGuy's Ramblings
Go back

Techniques for Writing Robust, Reliable Bash Scripts

Safer Scripting: Because Who Needs Errors, Anyway?

When it comes to bash scripting, safety should always be your top priority. After all, you don’t want your script to go rogue and wreak havoc on your system, do you? To avoid common errors and ensure your script behaves as expected, start with a solid foundation. Here’s a prolog that’ll take care of two very common mistakes:

#!/bin/bash
set -o nounset
set -o errexit

The first line, #!/bin/bash, specifies the interpreter that should be used to run your script. The second line, set -o nounset, prevents your script from referencing undefined variables, which can lead to unexpected behavior. The third line, set -o errexit, ensures that your script exits immediately if any command fails, preventing further errors from propagating.

But what if you need to tolerate a failing command? No worries! You can use the following idiom to ignore errors:

if ! <possible failing command> ; then
    echo "failure ignored"
fi

Some Linux commands also have options that can suppress failures. For example, mkdir -p will create a directory and its parents if they don’t exist, without complaining if the directory already exists. Similarly, rm -f will remove a file without prompting for confirmation, even if the file doesn’t exist.

Additional Tips and Tricks:

Next, I’ll move on to the section on functions in bash. Here’s the rewritten section:

Functions in Bash: Because Code Reuse is a Good Thing

Bash functions are a great way to organize your code and make it more reusable. They’re essentially blocks of code that can be called multiple times from different parts of your script. Here’s an example of a simple function that extracts comments from a file:

ExtractBashComments() {
    egrep "^#"
}

You can call this function like any other command, passing a file as an argument:

cat myscript.sh | ExtractBashComments

Or, you can use it in a pipeline:

comments=$(ExtractBashComments < myscript.sh)

Additional Tips and Tricks:


Share this post on:

Previous Post
Understanding and Optimizing Docker’s daemon.json File
Next Post
Disabling Discord’s Activity Tracking