如何在 if 语句中捕获错误

Luc*_*one 3 error-handling bash if-statement bash-trap

运行以下代码:

#!/bin/bash

set -o pipefail
set -o errtrace
set -o nounset
set -o errexit

function err_handler ()
{
    local error_code="$?"
    echo "TRAP!"
    echo "error code: $error_code"
    exit
}
trap err_handler ERR

echo "wrong command in if statement"

if xsxsxsxs 
    then
        echo "if result is true"
    else
        echo "if result is false"
fi

echo -e "\nwrong command directly"
xsxsxsxs 

exit
Run Code Online (Sandbox Code Playgroud)


产生以下输出:

wrong command in if statement
trap.sh: line 21: xsxsxsxs: command not found
if result is false

wrong command directly
trap.sh: line 29: xsxsxsxs: command not found
TRAP!
error code: 127
Run Code Online (Sandbox Code Playgroud)


如何在 if 语句中捕获“未找到命令”错误?

Ger*_*cia 5

您不能在 if 中为测试捕获 ERR

来自 bash 人:

The ERR trap is not executed if the failed  command
is  part  of  the  command list immediately following a while or
until keyword, part of the test in an if statement,  part  of  a
command  executed in a && or || list, or if the command's return
value is being inverted via !
Run Code Online (Sandbox Code Playgroud)

但你可以改变这一点

if xsxsxsxs 
then ..
Run Code Online (Sandbox Code Playgroud)

对此

xsxsxsxs 
if [[ $? -eq 0 ]]
then ..
Run Code Online (Sandbox Code Playgroud)