Mort
Mort

Reputation: 3549

bash - Exiting current function by calling another function?

Is it possible to have a function (or something similar) in bash that when called, will return from its calling function?

Let me explain... In my shell scripts I have some some common functions that I can use everywhere

function die () { echo "$0: ERROR : ${2:-} $(date)"; <script-specific cleanup>; exit $1; }
# Example use
[ $count -lt 5 ] && die 1 "Incorrect usage count='$count' must be >5."

Which is great if you want to exit your script entirely. But can you "Do some common cleanup tasks and exit the current function" in a function (or something similar)? Obviously, the return in the function below will simply return from die_fn and not from its caller.

# This of course is no good
function die_fn () { echo "$0: ERROR : ${2:-} $(date)"; <cleanup>; return $1; }
function foo ()
{
    ...
    [ $found -eq 0 ] && die_fn 1 'No targets founds. Skipping build'
    ...
}

You could, I suppose, put echo "$0: ERROR : ${2:-} $(date)"; <script-specific cleanup>; return $1; in die_fn.sh and source it when needed, but that is a lot of work for what is supposed to be a simplification.

Update It seems very likely that this is not possible in any elegant and maintainable way. Barring any new revelations, I suspect I will just append && return 1 to the line when I want brevity, and have a full if statement when that's not desired.

Upvotes: 1

Views: 506

Answers (1)

randomir
randomir

Reputation: 18697

The closest approximation of such behavior (that I can think of), would be to define the parent function (foo) as a subshell compound command (if that's acceptable for your use case), and then simply use exit in die function to exit the innermost shell (i.e. the parent foo function).

For example:

#!/bin/bash

die() { echo "$0: DIE: ${2:-} $(date)"; exit "$1"; }

foo() (
    echo "In foo"
    die 1 'No targets found. Skipping build'
)

foo
echo "foo exited with $?"

The result:

In foo
./script.sh: DIE: No targets found. Skipping build Sun 19 Nov 21:18:42 CET 2017
foo exited with 1

Upvotes: 1

Related Questions