first, how to debug
1. Parameters through the SH command:
SH [-NVX] Scripts. SH options and Parameters:-N: Do not execute script, query syntax only;-V: Before executing sccript, output the contents of scripts to the screen;-x: script to be used The content is displayed on the screen, which is a useful parameter!
Sample 1:no news is good news
sh -n add1_100. SH
Example 2:
sh -n add1_100. SH add1_100. sh: Line 12: syntax error: unexpected end of file
1#!/bin/Bash2 #简介略3 ##########4DECLARE i=15Declaresum=06 while[${i}-leTen]7 Do8sum1=$ ((${sum}+${i}))9i=$ ((${i}+1))Ten done1 One Echo "The total is ${sum}"
Example 3: Use-X to display what is performed:
[Email protected] tmp]#SH-X add1_100.SH+ Declare i=1+ Declaresum=0+'[' 1-le'Ten]'add1_100.SH: section6Line: [: Missing ']'+Echo 'The total is 0' The total is0 [email protected] tmp]#
1#!/bin/Bash2 #简介略3 ##########4DECLARE i=15Declaresum=06 while[${i}-leTen]7 Do8sum1=$ ((${sum}+${i}))9i=$ ((${i}+1))Ten Done One Echo "The total is ${sum}"
The last bracket in line six is missing a space!
2. Using the Debug hooks
3. Use the "Debug hooks"
a friend of the C language program has this impression: We often use the debug macro to control whether or not to output debug information, and in shell scripts we can also use such a mechanism, as shown in the following code:
if ["$DEBUG" = "truethenecho " debugging " #此处可以输出调试信息 fi
such blocks of code are often referred to as "debug hooks" or "Debug blocks". Inside the debug hook can output any of the debugging information you want to output, the advantage of using debug hooks is that it can be controlled by the debug variable, in the development and debugging stage of the script, you can first execute the Export debug=true command to open the debug hook, so that it output debugging information, And when the script is delivered to use, there is no need to bother to delete debug statement one by one in the script.
If you use the IF statement to determine the value of the debug variable in every place where you need to output debugging information , it is still cumbersome to define a debug function to make the process of inserting the debug hooks more concise and convenient, as shown in the following code:
$Cat–n Exp3.SH 1DEBUG ()2 { 3 if["$DEBUG"="true"]; Then 4[email protected]5 fi 6 } 7A=1 8DEBUGEcho "a= $a" 9 if["$a"-eq1 ] Ten Then Oneb=2 A Else -b=1 - fi theDEBUGEcho "b= $b" -C=3 -DEBUGEcho "c= $c"
In the debug function shown above, any commands passed to it will be executed, and the execution can be controlled by the value of the debug variable, so it is convenient to call all debug-related commands as parameters of the debug function.
More ways to stay updated ...
Getting Started with Linux fifth day--shell script Getting Started (bottom) debugging debug of Basic grammar