如何禁用單一命令的 set -e ?

如何禁用單一命令的 set -e ?

當任何指令傳回非零退出程式碼時,set -e 指令會使 bash 腳本立即失敗。

  1. 是否有一種簡單而優雅的方法來禁用腳本中單一命令的此行為?

  2. Bash 參考手冊中記錄了此功能的哪些位置(http://www.gnu.org/software/bash/manual/bashref.html)?

答案1

  1. 像這樣的事情:

    #!/usr/bin/env bash
    
    set -e
    echo hi
    
    # disable exitting on error temporarily
    set +e
    aoeuidhtn
    echo next line
    
    # bring it back
    set -e
    ao
    
    echo next line
    

    跑步:

    $ ./test.sh
    hi
    ./test.sh: line 7: aoeuidhtn: command not found
    next line
    ./test.sh: line 11: ao: command not found
    
  2. set內建幫助中對此進行了描述:

    $ type set
    set is a shell builtin
    $ help set
    (...)
    Using + rather than - causes these flags to be turned off.
    

此處記錄了相同的內容:https://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin

答案2

取消錯誤保釋的另一個選項是無論如何都要強製成功。你可以這樣做:

cmd_to_run || true

這將傳回 0 (true),因此不應觸發 set -e

答案3

如果您試圖捕獲返回/錯誤代碼(函數或 fork),則可以使用以下方法:

function xyz {
    return 2
}

xyz && RC=$? || RC=$?

答案4

另一種方法,我發現相當簡單(並且適用於set除 之外的其他選項-e):

使用它$-來恢復設定。

例如:

oldopt=$-
set +e
# now '-e' is definitely disabled.
# do some stuff...

# Restore things back to how they were
set -$oldopt

儘管-e具體而言,其他人提到的選項(|| true或「放入」內if)可能更慣用。

相關內容