SoFunction
Updated on 2025-03-09

Built-in debugging techniques for Bash scripts

Scripts written in Bash can also be debugged, just like interpreted languages ​​such as Python and Perl. Create a new script called servinfo and add executable permissions:

Copy the codeThe code is as follows:

$ vi servinfo

#!/bin/bash

echo "Hostname: $(hostname)"
echo "Date: $(date)"
echo "Kernel: $(uname -mrs)"

$ chmod +x servinfo


Use bash -x to debug the above script. Bash first prints out each line of script, and then prints out the execution result of each line of script:
Copy the codeThe code is as follows:

$ bash -x servinfo
++ hostname
+ echo 'Hostname: vpsee'
Hostname: vpsee
++ date
+ echo 'Date: Thu Sep  3 19:33:48 SAST 2009'
Date: Thu Sep  3 19:33:48 SAST 2009
++ uname -mrs
+ echo 'Kernel: Linux 2.6.18-128.4.1.el5 i686'
Kernel: Linux 2.6.18-128.4.1.el5 i686

If you want to print line numbers at the same time, you can add:
Copy the codeThe code is as follows:

export PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '

The execution result is:
Copy the codeThe code is as follows:

$ bash -x servinfo
+ export 'PS4=+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
+ PS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '
++4:5:: hostname
+4:5:: echo 'Hostname: vpsee'
Hostname: vpsee
++4:6:: date
+4:6:: echo 'Date: Thu Sep  3 19:42:06 SAST 2009'
Date: Thu Sep  3 19:42:06 SAST 2009
++4:7:: uname -mrs
+4:7:: echo 'Kernel: Linux 2.6.18-128.4.1.el5 i686'
Kernel: Linux 2.6.18-128.4.1.el5 i686

If you want to debug only a few lines of scripts, you can use set -x and set +x to include the part you want to debug:
Copy the codeThe code is as follows:

#!/bin/bash

echo "Hostname: $(hostname)"
set -x
echo "Date: $(date)"
set +x
echo "Kernel: $(uname -mrs)"


At this time, you can run the script directly without executing bash -x:
Copy the codeThe code is as follows:

$ ./servinfo
Hostname: vpsee
++ date
+ echo 'Date: Thu Sep  3 19:46:53 SAST 2009'
Date: Thu Sep  3 19:46:53 SAST 2009
+ set +x
Kernel: Linux 2.6.18-128.4.1.el5 i686

If you want to debug a very complex Bash script, it is recommended to use a special debugging tool, such as:bashdb