Linux Shell script series tutorial (7): script debugging
This article mainly introduces the Linux Shell script series (7): script debugging. This article describes the Bash built-in debugging and custom debugging functions. For more information, see
I. debug the script
Debugging is one of the important features that every programming language should implement. When something unexpected occurs, use it to generate the script running information, debugging information helps you find out why the program crashes or has abnormal behavior.
Ii. Bash built-in debugging
By using Bash's built-in debugging function, you can debug the entire script or only some statements in the script.
# Use set-x and set + x to debug a script sentence
The Code is as follows:
#! /Bin/bash
For I in {1 2 3 4 5 6 };
Do
Set-x # enable debugging
Echo $ I # statements to be debugged
Set + x # disable debugging
Done
Echo "Script executed ."
The Code is as follows:
# Use the-x option to debug the entire script
Bash-x script. sh # equivalent to sh-x script. sh
Iii. Custom debugging
Bash's built-in debugging function can only output debugging information in a fixed format, but in many cases, we need to display debugging information in a custom format, this can be achieved through the _ DEBUG environment variable.
The Code is as follows:
# Run the following script using _ DEBUG = on bash script. sh
#! /Bin/bash
Function DEBUG ()
{
["$ _ DEBUG" = "on"] & &$ @ |: # DEBUG with _ DEBUG environment variables
}
For I in {1 2 3}
Do
DEBUG echo $ I
Done
We run DEBUG in front of every statement that needs to print debugging information. If _ DEBUG = on is not passed, the debugging information will not be printed. In Bash, tell shell not to perform any operation.