如何在if语句中捕获错误 [英] how to trap errors inside the if statement

查看:58
本文介绍了如何在if语句中捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码:

#!/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


产生以下输出:


produces the following output:

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


如何在if语句中也捕获"找不到命令"错误?

推荐答案

您不能在if中捕获用于测试的ERR

You can't trap ERR for the test in the if

来自bash man:

From bash man:

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 !

但是您可以更改此

if xsxsxsxs 
then ..

对此

xsxsxsxs 
if [[ $? -eq 0 ]]
then ..

这篇关于如何在if语句中捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆