0
0
Bash Scriptingscripting~5 mins

set -x for trace mode in Bash Scripting

Choose your learning style9 modes available
Introduction

Use set -x to see each command as it runs. It helps you understand what your script is doing step-by-step.

You want to find out why your script is not working as expected.
You want to learn how a script runs by watching each command.
You need to debug a script that has many commands.
You want to check the values of variables as the script runs.
Syntax
Bash Scripting
set -x
# your commands here
set +x

set -x turns on trace mode, showing commands before they run.

set +x turns off trace mode to stop showing commands.

Examples
This will show the ls command before listing files.
Bash Scripting
set -x
ls
set +x
Trace mode is only on for the pwd command here.
Bash Scripting
echo "Start"
set -x
pwd
set +x
echo "End"
Shows variable assignment and usage with trace mode.
Bash Scripting
set -x
VAR=hello
echo "$VAR"
set +x
Sample Program

This script shows commands as they run for pwd and ls. Then it stops tracing and prints "Done".

Bash Scripting
#!/bin/bash

# Turn on trace mode
set -x

# Show current directory
pwd

# List files
ls

# Turn off trace mode
set +x

echo "Done"
OutputSuccess
Important Notes

Trace mode helps find errors by showing exactly what runs.

Use set +x to avoid too much output after debugging.

Trace output starts with a plus sign + before each command.

Summary

set -x shows commands as they run to help debugging.

Turn it off with set +x when done.

Useful for understanding and fixing scripts step-by-step.