当前位置: 首页 > 知识库问答 >
问题:

Bash中是否有TRY CATCH命令

龙骏
2023-03-14

我正在编写外壳脚本,需要检查是否安装了终端应用程序。除非有更整洁的方法,否则我想使用TRY/CATCH命令来执行此操作。

共有3个答案

梁和颂
2023-03-14

我开发了一个几乎完美的尝试

try 
    echo 'Hello'
    false
    echo 'This will not be displayed'

catch 
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

你甚至可以把try-catch积木嵌套在里面!

try {
    echo 'Hello'

    try {
        echo 'Nested Hello'
        false
        echo 'This will not execute'
    } catch {
        echo "Nested Caught (@ $__EXCEPTION_LINE__)"
    }

    false
    echo 'This will not execute too'

} catch {
    echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"
}

该代码是我的bash样板/框架的一部分。它进一步扩展了try的概念

这是负责try的代码

set -o pipefail
shopt -s expand_aliases
declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us
alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;
           __oo__insideTryCatch+=1; ( set -e;
           trap \"Exception.Capture \${LINENO}; \" ERR;"
alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {
    local script="${BASH_SOURCE[1]#./}"

    if [[ ! -f /tmp/stored_exception_source ]]; then
        echo "$script" > /tmp/stored_exception_source
    fi
    if [[ ! -f /tmp/stored_exception_line ]]; then
        echo "$1" > /tmp/stored_exception_line
    fi
    return 0
}

Exception.Extract() {
    if [[ $__oo__insideTryCatch -gt 1 ]]
    then
        set -e
    fi

    __oo__insideTryCatch+=-1

    __EXCEPTION_CATCH__=( $(Exception.GetLastException) )

    local retVal=$1
    if [[ $retVal -gt 0 ]]
    then
        # BACKWARDS COMPATIBILE WAY:
        # export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"
        # export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"
        export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"
        export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"
        export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"
        return 1 # so that we may continue with a "catch"
    fi
}

Exception.GetLastException() {
    if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]
    then
        cat /tmp/stored_exception
        cat /tmp/stored_exception_line
        cat /tmp/stored_exception_source
    else
        echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"
    fi

    rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source
    return 0
}

可以自由地使用、使用和贡献——它在GitHub上。

琴宾鸿
2023-03-14

根据我在这里找到的一些答案,我为自己制作了一个小的帮助文件,以供我的项目使用:

#!/bin/bash

function try()
{
    [[ $- = *e* ]]; SAVED_OPT_E=$?
    set +e
}

function throw()
{
    exit $1
}

function catch()
{
    export ex_code=$?
    (( $SAVED_OPT_E )) && set +e
    return $ex_code
}

function throwErrors()
{
    set -e
}

function ignoreErrors()
{
    set +e
}

下面是它在使用中的外观示例:

#!/bin/bash
export AnException=100
export AnotherException=101

# start with a try
try
(   # open a subshell !!!
    echo "do something"
    [ someErrorCondition ] && throw $AnException

    echo "do something more"
    executeCommandThatMightFail || throw $AnotherException

    throwErrors # automaticatly end the try block, if command-result is non-null
    echo "now on to something completely different"
    executeCommandThatMightFail

    echo "it's a wonder we came so far"
    executeCommandThatFailsForSure || true # ignore a single failing command

    ignoreErrors # ignore failures of commands until further notice
    executeCommand1ThatFailsForSure
    local result = $(executeCommand2ThatFailsForSure)
    [ result != "expected error" ] && throw $AnException # ok, if it's not an expected error, we want to bail out!
    executeCommand3ThatFailsForSure

    # make sure to clear $ex_code, otherwise catch * will run
    # echo "finished" does the trick for this example
    echo "finished"
)
# directly after closing the subshell you need to connect a group to the catch using ||
catch || {
    # now you can handle
    case $ex_code in
        $AnException)
            echo "AnException was thrown"
        ;;
        $AnotherException)
            echo "AnotherException was thrown"
        ;;
        *)
            echo "An unexpected exception was thrown"
            throw $ex_code # you can rethrow the "exception" causing the script to exit if not caught
        ;;
    esac
}
欧阳安晏
2023-03-14

Bash中有TRY-CATCH命令吗?

Bash并没有在许多编程语言中能找到的那么多奢侈品。

bash中没有try/catch;然而,使用

使用| |

如果command1失败,则command2运行如下

command1 || command2

类似地,使用

try/catp最接近的近似值如下

{ # try

    command1 &&
    #save your output

} || { # catch
    # save log for exception 
}

bash还包含一些错误处理机制

set -e

如果任何简单的命令失败,它会停止您的脚本。

如果。。。否则。这是你最好的朋友。

 类似资料:
  • 问题内容: bash中是否有“ goto”语句?我知道这被认为是不好的做法,但是我需要特别的“ goto”。 问题答案: 不,那里没有; 有关 确实 存在的控制结构的信息,请参见《 Bash参考手册 》中的第3.2.4节“复合命令” 。特别要注意的是,和的提及不如灵活,但是在Bash中比某些语言更灵活,并且可以帮助您实现所需的目标。(无论您想要什么……。) __

  • 基础常用命令 某个命令 --h,对这个命令进行解释 某个命令 --help,解释这个命令(更详细) man某个命令,文档式解释这个命令(更更详细)(执行该命令后,还可以按/+关键字进行查询结果的搜索) Ctrl + c,结束命令 TAB键,自动补全命令(按一次自动补全,连续按两次,提示所有以输入开头字母的所有命令) 键盘上下键,输入临近的历史命令 history,查看所有的历史命令 Ctrl +

  • 我在本地回购中做了很多更改,包括删除了数千个文件,并进行了数百次更改。与此同时,我对另一台计算机进行了文件同步(只是无法访问internet),然后继续创建数千个文件,删除数千个文件,并进行数百次更改。现在回购协议运行良好,因为我从后来使用的计算机上更新了它,但当我想拉到以前的计算机上时,这就变成了一场噩梦。。。显然,我必须手动签出我删除或更改的所有文件,并恢复到最后一个头部,然后再拉。。。是否有

  • 问题内容: 这是我的方法: 表名是小写,下划线的用途来分隔词语,并且是单数(例如,等 我通常(并非总是)具有自动增量PK。我用下面的约定:(例如,等)。 当表包含作为外键的列时,我只需从它来自的任何表中复制该键的列名。例如,假设表格具有FK (的PK )。 在定义FK来强制引用完整性时,我使用以下代码:(例如,扩展示例3,它将是)。由于这是表名/列名的组合,因此可以保证它在数据库中是唯一的。 我按

  • 本文向大家介绍bash shell 中的 hash 命令有什么作用?相关面试题,主要包含被问及bash shell 中的 hash 命令有什么作用?时的应答技巧和注意事项,需要的朋友参考一下 答案: linux 命令’hash’管理着一个内置的哈希表,记录了已执行过的命令的完整路径,用该命令可以打印出你所使用过的命令以及执行的次数。 [root@localhost ~]# hash hits co

  • 问题内容: 我正在Linux中编写bash shell脚本,该程序将接受日期(mm-dd- yyyy)作为参数。我想知道是否有一种简单的方法来检查日期是否有效?有操作员,我可以使用测试进行检查吗? 问题答案: 您可以检查 因此是有效的,但是使用连字符(例如)对于无效。 您也可以使用单词:或都有效。