sh脚本和bash脚本
How to debug a Bash script if it has some bugs? Common techniques like printing varibles out for checking apply for bash too. For bash, I also use 2 bash-specific techniques.
如果Bash脚本有一些错误,该如何调试 ? 诸如打印变量以进行检查之类的常见技术也适用于bash。 对于bash,我还使用2种特定于bash的技术。
使用errexit选项 (Use errexit option)
Run the script with -e
option like bash -e your-script.sh
or add set -o errexit
to the beginning of the script.
使用-e
选项(如bash -e your-script.sh
运行脚本,或将set -o errexit
添加到脚本的开头。
errexit
makes bash exit immediately if one statement’s return code is not 0. This way, you know which statement goes wrong.
如果一个语句的返回码不为0,则errexit
会使bash立即退出。这样,您就知道哪个语句出错。
使用xtrace选项 (Use xtrace option)
Run the script with -x
option like bash -x your-script.sh
or add set -o xtrace
to the beginning of the script.
使用-x
选项(如bash -x your-script.sh
运行脚本,或将set -o xtrace
添加到脚本的开头。
The -x
option will make bash print statements executed so that you know what is going on.
-x
选项将使bash 打印语句执行,以便您了解发生了什么。
一个例子 (One example)
For example,
例如,
#!/bin/bash
set -x
i=0
let i=i+1
echo $i
false # this will stop the script run with -e
date
The execution of that script with bash -e script.sh
will print
使用bash -e script.sh
执行该脚本将打印
+ i=0
+ let i=i+1
+ echo 1
1
+ false
By combining the 2 techniques together, which statement/step went wrong is printed out on the STDOUT.
通过将两种技术结合在一起,哪个语句/步骤出错了,将在STDOUT上打印出来。
翻译自: https://www.systutorials.com/how-to-debug-a-bash-script/
sh脚本和bash脚本