Bash – How to Alias ‘sudo !!’

aliasbashcommand historyhistory-expansionsudo

I'm trying to set an alias for sudo !! in Bash. I tried alias sbb='sudo !!', but it interprets that as a literal !! and prints

sudo: !!: command not found

If I use double quotes, it substitutes the double bang in the string itself, so that doesn't work.

Is there any way to make this work? Or an alternative alias?
`

Best Answer

!! is expanded by bash when you type it. It's not expanded by alias substitution.

You can use the history built-in to do the expansion:

alias sbb='sudo $(history -p !!)'

If the command is more than a simple command (e.g. it contains redirections or pipes), you need to invoke a shell under sudo:

alias sbb='sudo "$BASH" -c "$(history -p !!)"'
Related Question