0

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() {
  output=$(!!)
  # 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?

2

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'
/home2/ahq
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.