I know it’s an old question, but no one has addressed the issue with recursion yet.
There is a clean way of copying recursive functions, relying on an obscure corner of Bash. So obscure, in fact, that finding an application for it came as a surprise to me. So here is it.
However, as explained below, this trick is not enough to handle all recursive functions. That is why I also present another solution, which may be more straightforward but also much more costly.
A partial solution using aliases
Explanation
From man bash, section “ALIASES” (emphasis mine):
The rules concerning the definition and use of aliases are somewhat
confusing. Bash always reads at least one complete line of input,
and all lines that make up a compound command, before executing any of
the commands on that line or the compound command. Aliases are
expanded when a command is read, not when it is executed. Therefore,
an alias definition appearing on the same line as another command does
not take effect until the next line of input is read. The commands
following the alias definition on that line are not affected by the
new alias. This behavior is also an issue when functions are
executed. Aliases are expanded when a function definition is read,
not when the function is executed, because a function definition is
itself a command. As a consequence, aliases defined in a function are
not available until after that function is executed. To be safe,
always put alias definitions on a separate line, and do not use alias
in compound commands.
Otherwise said, when a function is defined, all occurrences in its body of aliases which exist at that time are expanded. (And, conversely, no alias expansion takes place when the function is called.) This can be exploited to substitute recursive calls inside a function body, without resorting to dirty, unsound sed invocations.
As already explained by other answers, the body of the function to copy can be obtained with declare -fp $old_name. You then put the new name of the function on top of this body instead of the old name (using Bash’s variable substitution mechanism), and feed the whole thing to eval to define the new function.
Code
The code presented below is written in the spirit of @ingidotnet’s excellent answer, adding to it support for recursive functions.
- It only uses shell builtins, no external programs (such as
tail or sed).
- It does not perform unsound, textual substitutions (well, except for a very small assumption about the output format of
declare -fp).
- It is correctly quoted.
- It supports copying some recursive functions.
However there is a pitfall: the alias trick apparently does not catch all possible recursive calls. It misses at least the calls of the form $(old_name ...).
function copy_function() {
declare old="$1"
declare new="$2"
# input checks:
if [[ ! "$old" =~ ^[a-zA-Z0-9._-]+$ ]] ; then
printf >&2 'copy_function: %q is (probably) not a valid function name\n' "$old"
return 1
elif [[ ! "$new" =~ ^[a-zA-Z0-9._-]+$ ]] ; then
printf >&2 'copy_function: %q is (probably) not a valid function name\n' "$new"
return 1
fi
# find the definition of the existing function:
declare def ; def="$(declare -fp "$old")" || return
# create an alias, in order to substitute $old for $new in function body:
declare former_alias="$(alias "$old" 2>/dev/null)"
alias "$old=$new"
# define the function $new:
eval "${def/#$old ()/$new ()}"
# remove the alias, restoring the former one if needed:
unalias "$old"
[ -n "$former_alias" ] && eval "$former_alias" || true
}
rename_function() {
copy_function "$@" || return
unset -f "$1"
}
Example 1
The following code:
# a recursive function which prints a range of numbers
function enum() {
declare -i i="$1"
declare -i j="$2"
if [ $i -gt $j ] ; then
return
elif [ $i -eq $j ] ; then
echo $i
else
declare -i k=$(( i + j ))
[ $k -lt 0 ] && k=$(( k-1 ))
k=$(( k / 2 ))
enum $i $k
enum $(( k+1 )) $j
fi
}
rename_function enum range
declare -fp enum range
range 1 5
will work as expected (tested with bash 5.0.7):
bash: declare: enum: not found
range ()
{
declare -i i="$1";
declare -i j="$2";
if [ $i -gt $j ]; then
return;
else
if [ $i -eq $j ]; then
echo $i;
else
declare -i k=$(( i + j ));
[ $k -lt 0 ] && k=$(( k-1 ));
k=$(( k / 2 ));
range $i $k;
range $((k+1)) $j;
fi;
fi
}
1
2
3
4
5
Example 2
However, the following recursive function won’t be properly renamed.
# the Fibonacci function
function fib() {
declare -i n="$1"
if [ $n -le 1 ] ; then
echo $n
else
declare -i x=$(fib $(( n-2 )))
declare -i y=$(fib $(( n-1 )))
echo $(( x + y ))
fi
}
rename_function fib FIB
declare -fp fib FIB
FIB 5
The output is:
bash: declare: fib: not found
FIB ()
{
declare -i n="$1";
if [ $n -le 1 ]; then
echo $n;
else
declare -i x=$(fib $(( n-2 )));
declare -i y=$(fib $(( n-1 )));
echo $(( x + y ));
fi
}
bash: fib: command not found
bash: fib: command not found
0
A complete but heavier solution using function re-definitions
Here is an alternative approach. Simply define the new function as a wrapper function which re-defines the original function locally and calls it.
As compared to the alias trick, this tackles all recursive calls, but is much more costly, as the original function is be re-defined and restored at every call of the new function.
Code
Here is the code corresponding to that idea. To the best of my knowledge, it has no remaining flaw.
function copy_function() {
declare old="$1"
declare new="$2"
# input checks:
if [[ ! "$old" =~ ^[a-zA-Z0-9._-]+$ ]] ; then
printf >&2 'copy_function: %q is (probably) not a valid function name\n' "$old"
return 1
elif [[ ! "$new" =~ ^[a-zA-Z0-9._-]+$ ]] ; then
printf >&2 'copy_function: %q is (probably) not a valid function name\n' "$new"
return 1
fi
# find the definition of the existing function:
declare def ; def="$(declare -fp "$old")" || return
# define the new function as a wrapper around the old function:
eval "$(printf '
function %s() {
# save the current function $old, if any:
declare former_def="$(declare -fp %s 2>/dev/null)"
# re-define the original function $old:
%s
# call the original function $old:
%s "$@"
# restore the current function $old, if any:
declare -i ret=$?
if [ -z "$former_def" ] ; then
unset -f %s
else
eval "$former_def"
fi
return $ret
}
' "$new" "$old" "$def" "$old" "$old"
)"
}
Example 2
This time, example 2 from above works as expected:
bash: declare: fib: not found
FIB ()
{
declare former_def="$(declare -fp fib 2>/dev/null)";
function fib ()
{
declare -i n="$1";
if [ $n -le 1 ]; then
echo $n;
else
declare -i x=$(fib $(( n-2 )));
declare -i y=$(fib $(( n-1 )));
echo $(( x + y ));
fi
};
fib "$@";
declare -i ret=$?;
if [ -z "$former_def" ]; then
unset -f fib;
else
eval "$former_def";
fi;
return $ret
}
55