Premium lesson

Handling Errors & Debugging in Bash

Scripting·4 min read·Jan 1, 2025

In programming, error handling is the process of gracefully responding to and recovering from unexpected execution errors in a program.

On the other hand, debugging is the process of identifying and removing programming errors and faulty logic from a program.

These practices ensure that your script behaves predictably and provides meaningful feedback to both developers and users.

Testing the existence and values of variables

In scripting, the first strategy for preventing execution errors consists in verifying the existence and values of the different inputted or computed variables, before they are used by the other components of the script, such as functions and commands.

This helps improve the reliability of the script by ensuring that the data is initialized and in conformity with the expected type, and by avoiding executing functions and commands that are likely to fail due to invalid parameters, provoking unexpected crashes or behaviors.

This is usually done by creating conditions within if and elif statements using comparison operators, such as ==, -eq, or =~.

Since we've already covered strings and numbers comparison, we'll now cover nullity and filepaths validation.

Testing null variables

A null variable typically refers to a variable that hasn't been defined or initialized with a value.

variablevariable=""

To test if a variable is null, has zero length, or is undefined, you can use the -z operator:

[[ -z $variable ]]

On the other hand, to test if a variable is not null, you can use the -n operator

[[ -n $variable ]]
icon light bulb key

Unlock the CLI & Scripting with Bash module

Learn how to gain advanced control over the OS and automate complex routine tasks prone to manual errors with the CLI and Bash scripting.

You get immediate access to:

  • 34 focused lessons across the CLI and Bash
  • 4 real-world projects with commented solutions
  • Ongoing updates to this bundle
  • Lifetime access to this bundle
Unlock this module