SoFunction
Updated on 2025-03-10

How to debug Linux shell scripts

The shell also has a real debugging mode. If there is an error in the script "strangescript", you can debug it like this:

sh -x strangescript

This will execute the script and display the values ​​of all variables.

There is also a pattern in which the shell does not need to execute scripts and just check the syntax. Can be used like this:

sh -n your_script

This will return all syntax errors.

linux/unix shell l script debugging method

Shell provides some options for debugging scripts, as follows:

-n
Read the command in the script but not execute it, and is used to check for syntax errors in the script

-v
While executing the script, print the executed script command to standard error output

-x
Provide tracking execution information, and print out each command and result executed in sequence.

There are three ways to use these options. One is to provide parameters on the command line

$ sh -x ./2 is to provide parameters at the beginning of the script

#! /bin/sh -x The third method is to enable or disable parameters using the set command in the script

Copy the codeThe code is as follows:

#! /bin/sh
if [ -z "$1" ]; then
set -x
echo "ERROR: Insufficient Args."
exit 1
set +x


fiset -x and set +x respectively indicate that the -x parameters are enabled and disabled, so that only a certain segment in the script can be tracked and debugged.