Shell script debugging and problem judgment
Article Directory
Script debugging and problem judgment
[root@localhost ~]#sh [-nvx] script file
Options and parameters:
-n: Do not execute the script, only query syntax issues;
-v: Before executing the script, output the contents of the script to the screen;
-x: display the used script content (execution process) on the screen
1. Syntax query
Script file for the sum of integers from 1 to 100
#!/bin/bash
sum=0
i=0
while [ ${i} -ne 100 ]
do
i=$[$i+1]
sum=$[$sum+$i]
done
echo "运算结果是:$sum"
Next, I deliberately changed the last quotation marks to Chinese symbols to verify
And the return value is not 0
[root@localhost ~]#sh -n sum1.sh
sum1.sh:行9: 寻找匹配的 `"' 是遇到了未预期的文件结束符
sum1.sh:行10: 语法错误: 未预期的文件结尾
[root@localhost ~]#echo $?
2
Then we correct the characters and test the script again for grammatical problems
2. View the execution process
Example 2:
From 1 to the cumulative integer sum of the user input value, use the sh -x script file to view the execution process
- The script file is
#!/bin/bash
read -p "请输入整数值(1-100):" nu
sum=0
i=0
while [ ${i} -ne ${nu} ]
do
i=$[$i+1]
sum=$[sum+i]
done
echo "从1到${nu}的运算结果是:$sum"
- View the execution process
3. Two options sh -vx script file are also available
When you come to view the contents of the script file, you can view the execution process of the script, and the idea will be clearer!
Here I use a function script to verify, as follows
#!/bin/bash #所用shell
function db1 { #db1是函数名
read -p "请输入:" value #value是变量名
return $[$value * 2] #返回值取所输入的变量名的值和2的乘积的结果值
}
db1 #调用函数
echo $? #输出返回值(输出上个命令执行结果的返回值)
4. Enter in command mode: set nu and press Enter to view the line number
When the number of script lines is particularly large, although the specified line is wrong, sometimes the human eye cannot count at all. You need to enter the English character colon ":" in the command mode to enter the last line mode, and then enter the set nu command and press Enter to list the contents of the script Corresponding number of rows