How Do You Perform Debugging in Linux Shell Scripting?


Angela Bailey

Debugging is an essential skill for any Linux shell scripter. It helps identify and fix errors, ensuring that your scripts run smoothly. In this article, we will explore various techniques to perform debugging in Linux shell scripting.

1. Enable Debugging Mode

If you want to enable debugging mode for your shell script, you can use the -x option. This option prints each command before executing it, giving you a clear view of the execution flow.

To enable debugging mode, add the following line at the beginning of your script:

set -x

2. Echo Statements

Echo statements are a simple yet effective way to debug shell scripts. By strategically placing echo statements at different points in your script, you can print variable values or custom messages to track the flow and identify any issues.


# Code snippet
echo "Starting the script.."

# Debugging line
echo "Variable value: $variable"

# Rest of the code

3. Redirect Output to a Log File

If your script generates a large amount of output, redirecting it to a log file can help analyze it more effectively. You can use the > symbol to redirect standard output (stdout) and >> to append output.

$ ./ > output.log    # Redirect stdout to a log file
$ .sh >> output.log   # Append stdout to an existing log file

4. Error Handling with ‘set -e’ and ‘trap’

When a command fails in your script, the default behavior is to continue executing the remaining commands.

However, this may lead to unexpected results. By using the set -e option, your script will exit immediately if any command fails.

set -e

# Code snippet

You can also define a custom error handling function using the trap command. This function will execute whenever an error occurs:

trap "custom_error_function" ERR

custom_error_function() {
    echo "Error occurred!"

5. Debugging with 'set -o'

The set -o command provides more options for debugging shell scripts:

  • -e: Exit immediately if a command exits with a non-zero status.
  • -u: Treat unset variables as an error and exit immediately.
  • -v: Print shell input lines as they are read.
  • -x: Print commands and their arguments as they are executed.
$ set -o errexit    # Equivalent to set -e
$ set -o nounset     # Equivalent to set -u
$ set -o verbose     # Equivalent to set -v
$ set -o xtrace      # Equivalent to set -x


In this article, we have explored several techniques for debugging in Linux shell scripting. By enabling debugging mode, using echo statements, redirecting output to a log file, handling errors with 'set -e' and 'trap', and utilizing the 'set -o' command, you can effectively identify and resolve issues in your shell scripts. Remember to use these techniques wisely to improve the efficiency and reliability of your scripts.