How to Use bash set x in Linux [4 Practical Examples]

Written by

Reviewed by

Last updated: July 24, 2024

Expert verified

SVG Image

TL; DR

Here are four ways to use bash set x for debugging your scripts in Linux:

  1. Tracing Shell Script Execution: Use set -x to print each command and argument as they run, making error identification easier.
  2. Debugging Recursive Functions: Enable set -x to display line numbers and commands causing errors in recursive scripts.
  3. Benchmarking Shell Scripts: Use set -x to track and measure the execution time of commands for performance insights.
  4. Improving Script Performance: Apply set -x to find and optimize slow-running commands in your script.

Read on to find out more about how to use bash set x in Linux command prompt from our comprehensive guide below.

Struggling to debug your Bash scripts?. Luckily, there’s an easy fix: the set -x option. This handy tool shows you detailed outputs of each command in your script, making it easier to spot and correct errors. In this post, I’ll show you how to use set -x, customize its settings, and apply best practices for effective debugging. By the end, you’ll be able to troubleshoot your scripts with ease and confidence.

What is set -x and Its Functionality

set -x is a command used in Bash scripting to help you debug your scripts. When you add set -x to your script, Bash starts printing each command and its arguments as they get executed. This helps you see exactly what your script is doing, making it easier to find and fix errors.

How set -x Works?

Imagine you have a script that isn’t working as expected. By including set -x at the beginning of your script, you can see a detailed trace of each command being run. This trace includes the command itself and any variables or arguments it uses. This way, if a command isn’t working correctly, you can spot where it goes wrong.

Example

Here’s a simple example to show how set -x works:

#!/bin/bash
set -x
name="Alice"
echo "Hello, $name"

When you run this script, the output will look something like this:

+ name='Alice'
+ echo 'Hello, Alice'
Hello, Alice

The + signs show the commands being executed. This output helps you understand the flow of your script and makes it easier to debug issues.

How to Use bash set x in Linux [4 Simple Ways]

To use bash set -x in Linux, start by adding set -x at the beginning of your script. This command prints each command and its arguments as they execute, helping you debug. You can also run a script with bash -x scriptname.sh from the command line for the same effect.

Here are four practical examples of how to use bash set x in Linux scripts:

1. Tracing Shell Script Execution

bash set x can be used to trace the execution of a shell script. This can be helpful in identifying errors and understanding how the script is executing. Here’s how to do it:

  1. Enable bash set x for tracing your script with the command below:
bash -x scriptname.sh
  1. You will see each command and its arguments printed to the console as they are executed.
tracing shell script execution bash set x

2. Debugging Recursive Function

bash set x can also be used for error handling and debugging for recursive functions. When an error occurs, this command will print the line number and the command that caused the error to the console. This can help you quickly identify the problem and fix it.

  1. To check the loop using the bash set x, execute the following command:
bash -x scriptname.sh
  1. The output will display each code line execution, along with the variable value in every loop.
error handling and debugging recursive functions bash set x

3. Benchmarking Shell Scripts

bash set x can be used to benchmark shell scripts. This enables you to print the execution time of each command, helping in identifying the commands that consume the most time during execution. Using this approach, you’ll be able to optimize your script performance and execution speed. Here’s an example to use this method:

  1. To enable bash set x for benchmarking, add the following command to your script:
set -x
start=$(date +%s.%N)
  1. Then, at the end of your script, add the following command:
end=$(date +%s.%N)
runtime=$(echo "$end - $start" | bc)
echo "Total runtime: $runtime seconds"
  1. This will print the total runtime of the script to the console.
benchmarking shell scripts

4. Improving Part of the Script

bash set x can also be used to improve the performance of shell scripts. By identifying which commands are taking the most time to execute, you can optimize those commands to run more efficiently. To do this in your bash script, follow the steps below:

  1. To enable bash set x for performance optimization, add the following command to your script in the beginning:
set -x
  1. Then, add the set command with the +x option at the end of your script file:
set +x 
  1. Save the script and run your script as normal in the command prompt:
./scriptname.sh

Replace the scriptname with the name of your script file.

  1. In the output, you can now debug the part of the script and then optimize those commands to run more efficiently.
enable performance optimization

Customization Options for bash set x in Linux

bash set x also provide several options that can be used to customize its behavior. Some of the most commonly used options include:

  • -e: Exit immediately if a command exits with a non-zero status.
  • -u: Treat unset variables as an error.
  • -v: Print each command before executing it.
  • -o pipefail: If any command in a pipeline fails, exit immediately.

Some of the more advanced options available for bash set x include:

  • -E: Passes the ERR trap through commands that run in a subshell or function.
  • -T: Display the time spent executing each command.
  • -a: Mark variables as exported when they are assigned a value.

3 Best Practices to Use the bash set x Command in Linux

set -x is a powerful feature of the Bash shell that can greatly simplify the process of debugging Bash scripts in Linux. However, to get the most out of it, there are 3 best practices for using the bash set x command in Linux that you should follow:

1. Selective Use

While set -x can be an incredibly useful tool for debugging Bash scripts, it can also produce a lot of output that can quickly overwhelm your Terminal screen. This can make it difficult to identify the specific commands and outputs that are relevant to your debugging process.

To avoid this issue, it’s a good idea to enable set -x only for the parts of your script that you’re currently debugging. This can be done by using the set -x command to enable tracing at the beginning of the section you want to debug and then using the set -x command to disable tracing at the end of that section. Here’s an example code:

Code:

#!/bin/bash
# Disable tracing
set +x
# Run some commands without tracing
echo "This command will not be traced"
echo "This command will not be traced"
# Enable tracing for a specific section of the script
set -x
echo "This command will be traced"
echo "This command will be traced"
set +x
# Run some more commands without tracing
echo "This command will not be traced"
echo "This command will not be traced"

Output:

selective use to avoid overwhelming terminal screen

2. Redirect Output

If you’re using set -x to debug a long-running Bash script, it can be helpful to redirect the output to a file instead of displaying it on the Terminal. This can make it easier to analyze the output later on without overwhelming your Terminal screen with a large amount of output.

To redirect the output of set -x to a file, you can use the > operator to redirect standard output. For example:

Code:

#!/bin/bash
# Enable tracing and redirect output to a file
set -x
exec > >(tee /tmp/debug.out) 2>&1
# Run some commands
echo "This command will be traced"
echo "This command will be traced"
echo "This command will be traced"
# Disable tracing and restore output
set +x
exec >/dev/tty 2>&1

Output:

redirecting output to analyse later on

3. Combine with Other Options

Bash provides a range of other options that can be used in conjunction with set -x to further customize its behavior. One such option is set -o verbose, which enables verbose mode and prints each command before it is executed.

The Verbose mode can be useful for providing additional context and information about the script’s execution. When used with set -x, it can provide even more detail about the script’s inner workings. Here’s an example of using set -o verbose with set -x:

Code:

#!/bin/bash
# Enable tracing and verbose mode
set -x
set -o verbose
# Run some commands
echo "This command will be traced and printed"
echo "This command will be traced and printed"
# Disable tracing and verbose mode
set +x
set +o verbose

Output:

enable verbose mode to print command

    In a Nutshell

    Using the set -x option in your Bash scripts to improve debugging and trace script execution. Enabling set -x gives you detailed command outputs, making it easier to spot and fix errors quickly. You can activate it from the command line or embed it in your scripts for better control.

    If this guide helped you, here are some other helpful topics:

    Frequently Asked Questions

    What are the benefits of using bash set -x?

    The benefits of using the bash set -x can be incredibly useful when debugging Bash scripts. Here are some of the main benefits:
    Improved visibility of script execution for identifying errors
    Faster debugging with a real-time view of script execution
    Greater control by seeing exactly what commands are being executed and how they’re being executed, allowing for informed decisions in modifying the code.

    Can bash set x be used with other programming languages besides Bash?

    No, bash set x is a tool specifically designed for use with the Bash shell and cannot be used with other programming languages. While other programming languages may have similar tools or commands for tracing and debugging code, they are specific to those languages and cannot be used with Bash scripts. It’s important to use the appropriate debugging tool for the specific language you’re working with to ensure the best debugging experience and accurate results.

    Is it possible to disable bash set x for a specific command in a script?

    Yes, you can disable bash set x for particular command in a script by using the -x option to disable tracing for that command. For example:
    set -x echo "This command will be traced" 
    set +x echo "This command will not be traced"

    In this example, the set -x command enables tracing, which means that the echo "This command will be traced" command will be printed to the console as it is executed. However, the set +x command disables tracing, so the echo "This command will not be traced" command will not be printed to the console.

    Are there any limitations to using bash set x in very large shell scripts?

    While bash set x can be used in large shell scripts, it’s important to be aware of its potential impact on performance. This is because enabling bash set x in very large shell scripts can cause significant overhead and slow down the execution of the script. If you need to use bash set x in a very large shell script, it’s important to be mindful of its impact on performance and use it only when necessary.

    Ojash

    Author

    Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

    Akshat

    Reviewer

    Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

    Share this article
    Shareable URL
    Prev Post

    6 Effective Ways to Check the Version of a Python Package in Linux?

    Next Post

    [Fixed] “Command Not Found: Docker Compose” Error in Linux – 4 Simple Ways

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Read next