It's been well documented that is's possible to unset
a Bash function. Consider this function:
ls() {
echo 'Executing';
# Call to original ls
}
which can be unset with unset -f ls
.
I want to build a wrapper function which will temporarily unset a function, call the original function, then reset the function back. I want to do this to execute code surrounding a programing without having to rename my function arbitrarily.
I've thought of several possible solutions to this problem, none of which I'm particularly satisfied with.
Method 1: Simply linking to the original executable
ls() {
echo 'Executing';
/bin/ls $@;
}
While this would achieve the desired effect, it's not ideal because it is dependent of knowing where the original ls
(in this case) is located ahead of time. This would break on any platform that didn't have ls
in /bin
Method 2: source
the function definition again once the method finishes executing
ls() {
echo 'Executing';
unset -f ls;
/bin/ls $@;
source ~/.bash_functions;
}
Method 3: Store the state of the function (attempted)
I couldn't get this one to work, but it seems like I should be able to capture the function, save it, then unset and reset the function, like so:
ls() {
echo 'Executing';
SAVED=`which ls`;
unset -f ls;
/bin/ls $@;
ls=$SAVED;
}
So, how can I unset a function to call the original then reset it in Bash? Thanks so much for your help!