shell 调试
shell脚本的调试
Shell本身提供一些调试方法选项:
-n,读一遍脚本中的命令但不执行,用于检查脚本中的语法错误。
-v,一边执行脚本,一边将执行过的脚本命令打印到标准输出。
-x,提供跟踪执行信息,将执行的每一条命令和结果依次打印出来。
使用这些选项有三种方法(注意:避免几种调试选项混用)
1.在命令行提供参数:$sh -x script.sh
2.脚本开头提供参数:#!/bin/sh -x
3.在脚本中用set命令启用or禁用参数:其中set -x表示启用,set +x表示禁用。
1. 运行脚本时,添加-x选项
$ bash -x script-name
$ bash -x domains.sh
$ sh -x script_name
2. 在脚本中开启编译选项
#!/bin/bash
clear
# turn on debug mode
set -x
for f in *
do
file $f
done
# turn OFF debug mode
set +x
ls
# more commands
说明:
set -x Prints the statements after interpreting metacharacters and variables
set +x Stops the printing of statements
set -v Prints the statements before interpreting metacharacters and variables
set -f Disables file name generation (using metacharacters)
3. 解释器参数
#!/bin/bash -xv
#!/bin/sh -x
4.使用Debug变量和函数来实现
#!/bin/bash
_DEBUG="on"
function DEBUG()
{
[ "$_DEBUG" == "on" ] && $@
}
DEBUG echo 'Reading files'
for i in *
do
grep 'something' $i > /dev/null
[ $? -eq 0 ] && echo "Found in $i file"
done
DEBUG set -x
a=2
b=3
c=$(( $a + $b ))
DEBUG set +x
echo "$a + $b = $c"
5. 使用日志打印
(1.)下载log4shell.sh脚本
https://github.com/fredpalmer/log4bash/blob/master/log4bash.sh
(2.)日志打印
#!/usr/bin/env bash
source log4bash.sh
log "This is regular log message... log and log_info do the same thing";
log_warning "Luke ... you turned off your targeting computer";
log_info "I have you now!";
log_success "You're all clear kid, now let's blow this thing and go home.";
log_error "One thing's for sure, we're all gonna be a lot thinner.";
# If you have figlet installed -- you'll see some big letters on the screen!
log_captains "What was in the captain's toilet?";
# If you have the "say" command (e.g. on a Mac)
log_speak "Resistance is futile";
相关链接
https://www.cyberciti.biz/tips/debugging-shell-script.html
https://www.cnblogs.com/anliven/p/6032081.html
【励志篇】:
古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。