History expansion seems to be expanded immediately, whereas other commands inside the body of a function are deferred until the function is called. Try defining the function at a shell prompt. I get bash: !-$CYCLE: event not found
immediately, before the function definition is complete.
I tried escaping the exclamation point, but this causes it to be treated literally once the function is called, instead of being processed as a history expansion.
One alternative is a combination of eval
and fc
:
function cyc {
CYCLE=3
eval $( fc -nl -$CYCLE -$CYCLE )
}
I'll forgo the usual warning about eval
because you'll simply be re-executing a command you previously ran, so caution will apply however you accomplish this. The given fc
command will print a range of commands from history (-n
suppresses the line number), and using the same value for the beginning and end of the range limits the output to a single command.