I am trying to write a bash function in my .bashrc that reruns the previous command in the history and does something useful with the captured output.

my_function() {
  # Do something with output

I am getting: bash: !!: command not found. I understand there is a difference between commands and shell builtins, but can't figure out how to run this builtin from a function, or its command equivalent, if it even exists. How can I rerun the previous shell command from within a bash function?

1 Answer 1


You can't do that. Just like alias expansion, the command history expansion is performed when the function is defined, not when it's used.

You can access the history directly with the fc builtin, though:

$ redo(){ cmd=$(fc -nl -1 -1); echo "redoing '$cmd'"; eval "$cmd"; }
$ pwd
$ refo
redoing '      pwd'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .