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.
  • Change return 1 to return (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;-)

Tags:

Function

Bash