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

https://www.thegeekdiary.com/how-to-debug-shell-scripts/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM