Shadowfen
Shadowfen

Reputation: 469

Trying to use trap to break out of a shell function

I am trying to write a shell function that will exit the function (but not the script) if an error occurs within it (specifically when a called command returns an error), and return an error code to the calling function.

As an example, for the script:

#!/bin/sh
on_error() {
    return 1
}

f() {
    echo 'function f'
    g
    echo "g returned $?"
}

g() {
    trap on_error ERR
    echo 'function g'
    false
    echo "boo"
}

f

I am getting back:

$ ./cc
function f
function g
boo
g returned 0

when I wish to be getting back:

$ ./cc
function f
function g
g returned 1

What do I need to do to get this?

If I change the on_error function to exit 1 like:

on_error() {
    return 1
}

then I get:

$ ./cc
function f
function g

to indicate that the whole script is exiting when it hits the 'false' command.

While it would be possible in this example case to simply check the error code of the commands inside of g and return an error if one of them fails, in my real case I want a test function to attempt to copy a dozen or more files from different locations to different destinations and stop the first time that one of them fails so that I can report a test failure and go on to the next test function.

Though I would prefer a /bin/sh solution, /bin/bash would be good too.

Upvotes: 1

Views: 311

Answers (1)

user4933750
user4933750

Reputation:

Is this what you want? (Bash only.)

#!/bin/bash

f() {
    echo 'function f'
    g
    echo "g returned $?"
}

g() {
    trap 'return 1' ERR
    echo 'function g'
    false
    echo "boo"
}

f

Upvotes: 1

Related Questions