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?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With