How do I rename a bash function?
Here's a way to eliminate the temp file:
$ theirfunc() { echo "do their thing"; }
$ eval "$(echo "orig_theirfunc()"; declare -f theirfunc | tail -n +2)"
$ theirfunc() { echo "do my thing"; orig_theirfunc; }
$ theirfunc
do my thing
do their thing
Further golfed the copy_function
and rename_function
functions to:
copy_function() {
test -n "$(declare -f "$1")" || return
eval "${_/$1/$2}"
}
rename_function() {
copy_function "$@" || return
unset -f "$1"
}
Starting from @Dmitri Rubinstein's solution:
- No need to call
declare
twice. Error checking still works. - Eliminate temp var (
func
) by using the_
special variable.- Note: using
test -n ...
was the only way I could come up with to preserve_
and still be able to return on error.
- Note: using
- Change
return 1
toreturn
(which returns the current status code) - Use a pattern substitution rather than prefix removal.
Once copy_function
is defined, it makes rename_function
trivial. (Just don't rename copy_function
;-)