How to Debug Shell Scripts Efficiently?

 ·  ☕ 1 

In a recent tutorial, CIH introduced a powerful technique for debugging Shell scripts that eliminates the need for inserting numerous echo statements into the code.

Simple Methodology

To enable this debugging method, execute the following command:

1
2
3
(exec 111> log ;
export SHELLOPTS BASH_XTRACEFD=111 PS4='($BASH_SOURCE:$LINENO:$FUNCNAME): ' ;
set -x ; ./cih.sh)

How It Works

  • exec 111> log
    This command opens a file named log for writing and associates it with file descriptor 111. Subsequent outputs can be redirected to this file.
  • export SHELLOPTS
  • BASH_XTRACEFD=111
  • PS4=’($BASH_SOURCE:$LINENO:$FUNCNAME): '
  • set -x
  • ./cih.sh

Assuming cih.sh contains a function to generate a random number:

1
2
3
4
5
6
#!/bin/bash
function my_func()
{
	var=$RANDOM
}
my_func

Expected Output

After running the command, the output in log will look something like this:

1
2
3
4
5
6
$ (exec 111> log ; export SHELLOPTS BASH_XTRACEFD=111 PS4='($BASH_SOURCE:$LINENO:$FUNCNAME): ' ; set -x ; ./cih.sh)

$ cat log
(:1:): ./cih.sh
(./cih.sh:8:): my_func
(./cih.sh:5:my_func): var=21742

Such advanced techniques significantly elevate the debugging process.


Meng Ze Li
Meng Ze Li
Kubernetes / DevOps / Backend