0
0
Bash Scriptingscripting~5 mins

Debugging with PS4 in Bash Scripting

Choose your learning style9 modes available
Introduction

Debugging with PS4 helps you see each command your script runs. It makes finding mistakes easier.

You want to find out why your script is not working as expected.
You need to see the order of commands running in your script.
You want to check the values of variables as the script runs.
You are learning how a bash script works step-by-step.
Syntax
Bash Scripting
PS4='+prefix_string ' 
set -x
# your script commands
set +x

PS4 sets the prefix shown before each command when debugging.

Use set -x to start showing commands, and set +x to stop.

Examples
This shows each command with DEBUG: before it.
Bash Scripting
PS4='+DEBUG: ' 
set -x
ls
set +x
This shows the line number before each command.
Bash Scripting
PS4='+Line $LINENO: ' 
set -x
pwd
set +x
This shows the current time before each command.
Bash Scripting
PS4='+$(date +"%T"): ' 
set -x
echo Hello
set +x
Sample Program

This script sets PS4 to show the line number before each command. It then prints a greeting.

Bash Scripting
#!/bin/bash
PS4='+Line $LINENO: '
set -x
name="Alice"
echo "Hello, $name!"
set +x
OutputSuccess
Important Notes

PS4 can include variables like $LINENO to show line numbers.

Remember to turn off debugging with set +x to avoid clutter.

Use debugging to understand scripts better, not just to fix errors.

Summary

PS4 sets the prefix for debug output in bash scripts.

Use set -x to start and set +x to stop debugging.

Debugging helps you see commands and find script problems easily.