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