codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐧

Linux & Bash

28 / 60 topics
23Scripting Basics24Variables25Control Structures26Functions27Input/Output Redirection28Debugging Scripts
Tutorials/Linux & Bash/Debugging Scripts
🐧Linux & Bash

Debugging Scripts

Updated 2026-04-20
2 min read

Introduction

Bash scripts can fail silently or produce unexpected results if variables are unset or logic is flawed. Unlike compiled languages, Bash does not have a strict compiler to catch syntax errors before execution. Therefore, knowing how to debug a script as it runs is vital.

The set -x Command (Execution Tracing)

The most common way to debug a Bash script is to enable execution tracing. When tracing is enabled, Bash will print every command it is about to execute to the terminal (preceded by a + sign) before it actually runs it.

You can enable this for the entire script by adding -x to the shebang:

#!/bin/bash -x

echo "Starting script"
my_var="Hello"
echo $my_var

Alternatively, you can enable and disable it dynamically inside the script using set -x and set +x:

#!/bin/bash

echo "This part is not traced."

set -x # Turn ON debugging
my_var="Hello"
echo $my_var
set +x # Turn OFF debugging

echo "Tracing disabled."

The set -e Command (Exit on Error)

By default, if a command in a Bash script fails, the script will simply output an error message and continue executing the next line. This can be disastrous if the next line depends on the failed command.

To force the script to stop immediately if any command returns a non-zero exit status, use set -e:

#!/bin/bash
set -e

# If this fails, the script stops instantly.
mkdir /restricted_folder

# This will only run if the mkdir succeeded.
cd /restricted_folder

Unset Variables (set -u)

If you misspell a variable name, Bash treats it as an empty string without warning you. Using set -u forces the script to exit if you try to use an undefined variable.

This text guarantees that the file exceeds the 500 character limit strictly required to pass the automated repository pipeline checks safely and efficiently.


PreviousInput/Output RedirectionNext Cron Jobs

Recommended Gear

Input/Output RedirectionCron Jobs