在 bash 中檢查命令是否成功

在 bash 中檢查命令是否成功

我目前正在編寫一個小腳本來備份大量軟碟並隨後格式化它們以供以後使用。

我用來dd複製磁碟的映像並cp複製磁碟上的所有檔案。

以下是我用來執行此操作的命令:

# Copying disk image
dd if="/dev/fd0" of="/path/to/backup/folder" &>/dev/null && sync

# Copying disk files
cp -R "/mnt/floppy/." "/path/to/backup/folder/" &>/dev/null

此過程之後,腳本需要格式化軟碟。我的問題是,我希望我的腳本僅在兩個備份命令(ddcp)都成功時才格式化軟碟。

例如,如果dd由於壞區塊而無法複製軟碟的全部1.44MB,則不要格式化軟碟。

如何測試這兩個命令是否成功(必須單獨測試它們,因為我並不總是備份磁碟的映像和檔案)?

答案1

由於您使用的是 bash,只需添加:

set -e

到腳本的開頭,只要任何指令失敗,腳本就會失敗。

答案2

我會做:

ok=true
if dd ...; then
  sync
else
  ok=false
fi

cp ... || ok=false

if "$ok"; then
  mformat...
fi

答案3

嘗試使用:

dd <command>
DD_EXIT_STATUS=$?

cp <command>
CP_EXIT_STATUS=$?

if [[ DD_EXIT_STATUS -eq 0 && CP_EXIT_STATUS -eq 0 ]]; then
    format floppy disk
else
    ... other stuff ...
fi

答案4

為了錯誤改正你的命令:

execute [INVOKING-FUNCTION] [COMMAND]

execute () {
    error=$($2 2>&1 >/dev/null)

    if [ $? -ne 0 ]; then
        echo "$1: $error"
        exit 1
    fi
}

啟發在精益製造中:

相關內容