0

I recently came across this ingenious bash alias to repeat the last issued command, but as sudo. This could be done by using sudo !! directly in the terminal after the failed command.

The alias I found is alias mycmd='sudo $(history -p \!\!)'

It's just not clear to me how this works.

Braiam
  • 35,991
apoc
  • 191

1 Answers1

3

$(history -p \!\!) is a way of getting the last command executed without adding it again to the history. From help history:

  -p    perform history expansion on each ARG and display the result
    without storing it in the history list

In bash, !! expands to the last command executed, but you cannot directly use this in aliases, since this expansion is performed well before alias expansion. (History expansion is one of the earliest to happen - it happens before even brace expansion (which is usually first).)

So, you have to use some way to get the last command executed, and that can be done using history -p, which expands !! the way the shell would.

Though I don't know why they escaped !. For me, it works fine without the backslashes.

muru
  • 72,889