Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

popd before return / exit function

Tags:

bash

In bash what is the proper way to popd before returning / exiting from a function? For example,

function fn () {
    pushd ~ >/dev/null
    if [ $1 = $2 ]; then
        return 0;
    elif [ $2 = $3 ]; then
        return 1;
    else
        return 2;
    fi
    popd >/dev/null
}

Am I supposed to write popd before each return? Or, should I be doing this another way?

like image 817
Rorschach Avatar asked Mar 11 '23 17:03

Rorschach


1 Answers

For this I'd probably do it this way:

fn() {
    pushd ~ >/dev/null
    if [ "$1" = "$2" ]; then
        ret=0
    elif [ "$2" = "$3" ]; then
        ret=1
    else
        ret=2
    fi
    popd >/dev/null
    return $ret
}

that way I wouldn't have to repeat the "cleanup" code before each return.

An alternative would be to do the work in a subshell and have that cd to the desired directory, though that subshell could not modify the parent's environment (which is part of what we want after all).

fn() (
    cd ~
    if [ "$1" = "$2" ]; then
        return 0
    elif [ "$2" = "$3" ]; then
        return 1
    else
        return 2
    fi
)
like image 200
Eric Renouf Avatar answered Mar 20 '23 02:03

Eric Renouf