有沒有辦法暫停shell腳本的執行以檢查環境狀態或執行隨機命令?
uj5u.com熱心網友回復:
Bash 或 shell 腳本沒有其他編程語言(如 Java、Python 等)那樣的除錯功能。
我們可以將echo "VAR_NAME=$VAR_NAME"命令放在我們想要記錄變數值的代碼中。
此外,更靈活的解決方案是將此代碼放在我們要除錯的 shell 腳本的開頭的某個位置:
function BREAKPOINT() {
BREAKPOINT_NAME=$1
echo "Enter breakpoint $BREAKPOINT_NAME"
set e
/bin/bash
BREAKPOINT_EXIT_CODE=$?
set -e
if [[ $BREAKPOINT_EXIT_CODE -eq 0 ]]; then
echo "Continue after breakpoint $BREAKPOINT_NAME"
else
echo "Terminate after breakpoint $BREAKPOINT_NAME"
exit $BREAKPOINT_EXIT_CODE
fi
}
export -f BREAKPOINT
然后,在我們需要中斷的代碼行,我們像這樣呼叫這個函式:
# some shell script here
BREAKPOINT MyBreakPoint
# and some other shell script here
那么 BREAKPOINT 函式將記錄一些輸出,然后啟動/bin/bash我們可以運行echo我們想要的任何或其他一些 shell 命令。當我們想繼續運行 shell 腳本的其余部分(釋放斷點)時,我們只需要執行exit命令。如果我們需要終止腳本執行,我們將運行exit 1命令。
uj5u.com熱心網友回復:
alias結合使用eval為您提供呼叫背景關系中斷點的基本功能:
#!/bin/bash
shopt -s expand_aliases
alias breakpoint='
while read -p"Debugging(Ctrl-d to exit)> " debugging_line
do
eval "$debugging_line"
done'
f(){
local var=1
breakpoint
echo $'\n'"After breakpoint, var=$var"
}
f
在斷點處,您可以輸入
echo $var
其次是
var=2
然后 Ctrl-d 退出斷點。
由于eval在while回圈中,請謹慎使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/321996.html
上一篇:如何修復資料過長的欄目
