Shell-Script
無法使用退出命令停止腳本 l 循環
我的腳本中有一個調試函式(通過 nemo.action 執行),它使用 zenith 彈出視窗詢問使用者是否要在發生錯誤時停止或繼續。但是,當這種情況發生在循環內時,
exit
腳本中的命令或將被完全忽略。反正沒有強制退出完全停止腳本嗎? 我希望它像渡渡鳥一樣死去! 它必須能夠殺死它自己..
這是我調試的一部分:
44:57.198 • Stopped while renaming file/directory - it failed 44:57.199 • Error triggered, issue: 44:57.201 • Stopped while renaming file/directory.\nSee debug log for more info... 45:20.563 • Stopping the script by user request due error. () ^^^ this line gets written to the log when the user choose to exit vvv but it continues to run the script until a new error occurs 45:20.564 • Could not find ‘/temp/sani.txt‘ Have no value to assign to $jdir0 45:20.566 • Error triggered, issue: 45:20.567 • Could not find ‘/temp/sani.txt‘ Have no value to assign to $jdir0 45:24.670 • Stopping the script by user request due error. () ^^^ and when pressing stop here, the script will halt..
它與被觸發的錯誤函式相同:
jerror () { enl jdbugen "Error triggered, issue:\n\n" jdbug "$@" debuglogread=$(tail -10 "$debuglog") zenity --question --text="($jdec)Error Triggered\nIssue:\n\n ‘$@‘\n\n$debuglogread\n\nContinue?" --width=400 --height=200 jdec=$? if [ "$jdec" != 0 ] then jdbug "Stopping the script by user request due error. ($jdeck)" exit 1 else jdbug "User choose to continue the script" fi enl }
這部分腳本正在呼叫函式:
mv -f -v "$item" "$path/$name" &>> $debuglog # Rename jok=$? if [ $jok -ne 0 ] then jdbug "Stopped while renaming file/directory - it failed" jerror "Stopped while renaming file/directory.\nSee debug log for more info..." fi
我發現這並不容易,所以我通過將退出請求儲存在一個文件中來解決它。
通過添加字元串
printf "%d" "1" > "/tmp/exitcode.dat"
,我將值 1 儲存在一個臨時文件中。printf "%d" "1" > "/tmp/exitcode.dat" # Storing the exit code exit 1 # Will break of of the loop
在循環“完成”命令之後,您將需要重新讀取文件
if [[ -f "/tmp/exitcode.dat" ]] then jexit="$(</tmp/exitcode.dat)" # Read the stored code rm "/tmp/exitcode.dat" # Clean up and remove the file if [ $jexit eq 1 ]; then exit 1; # Check if exit code is 1 fi
更短的程式碼是創建文件。
touch "/tmp/exitcode.dat" # Create the file exit 1 # Exit the loop
在完成命令之後
if [[ -f "/tmp/exitcode.dat" ]]; Then # See if the file exists rm "/tmp/exitcode.dat" # Cleanup exit 1 # Exit the script fi