helpermethod
helpermethod

Reputation: 62165

Simulating exception-like bevaviour in bash

In Bash, is there some way to simulate exceptions?

E.g. in a test function, i have several test statements

test_foo_and_bar() {
    expect_foo $1
    expect_bar $2
}

expect_foo() {
    [[ $1 != "foo" ]] && return 1
}

expect_bar() {
    [[ $1 != "bar" ]] && return 1
}

Now, what I would want is that if expect_foo fails, execution stops and returns to the caller of function test_foo_and_bar.

Is something like that possible? I know you could do something like this:

test_foo_and_bar() {
    expect_foo $1 || return 2
    expect_bar $2 || return 2
}

But I am interested in alternative solutions (if there are any).

EDIT

While the proposed solutions are pretty good, I have one further requirement. After an exception has occured, I still need to perform cleanup. So just exiting is not an option.

What I effectivly need, in Java-speak, is some sort of finally clause.

Upvotes: 1

Views: 106

Answers (1)

Michał Górny
Michał Górny

Reputation: 19233

A quick hack that comes to my mind is to use subshelling and exit:

test_foo_and_bar() {
    (
        expect_foo $1
        expect_bar $2
    )
}

expect_foo() {
    [[ $1 != "foo" ]] && exit 1
}   

expect_bar() {
    [[ $1 != "bar" ]] && exit 1
}   

This way, any failure will cause the whole test_foo_and_bar block to terminate. However, you will always have to remember to call expect_foo and _bar in a subshell to avoid terminating the main program.

Additionally, you'll likely want to replace the exit with a custom die function which will output some verbose error as well.

Upvotes: 1

Related Questions