Popd before return / exit function

In bash, what is the correct way popdbefore returning / exiting a function? For instance,

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

Should I write popdbefore each return? Or should I do it differently?

+4
source share
1 answer

For this, I would do this:

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
}

this way I wouldn’t have to repeat the “clear” code before each return.

An alternative would be to do the work in a subshell and have it cdin the desired directory, although this subshell cannot change the parent environment (which is part of what we want in the end).

fn() (
    cd ~
    if [ "$1" = "$2" ]; then
        return 0
    elif [ "$2" = "$3" ]; then
        return 1
    else
        return 2
    fi
)
+7
source

Source: https://habr.com/ru/post/1660119/


All Articles