Sometimes when I run a command I don't notice that I needed to run it as super user to have enough permission.
Is there a way to run the same command again but as a super user?
Sometimes when I run a command I don't notice that I needed to run it as super user to have enough permission.
Is there a way to run the same command again but as a super user?
The simplest way is to run:
This will run the last command but as super user.
Source.
Answer: you enter
sudo !!
straight afterwards to repeat the previous command with escalated privileges.edit: Image found via reddit, and it's a parody of the original xkcd comic by Randall Munroe.
You could try the up-arrow key to scroll through your old commands and rewrite/change them and add the
sudo
in front of them. (the home button above the arrow keys will set the position to the beginning.)I dislike the
sudo !!
idea, because sometimes you add another command in between and don't remember anymore.This question could have been generalized into "Run same command but with some modification", since one of the brilliant design decisions in Unix, is that what's implemented once in the shell, can be leveraged by any command being invoked from the shell.
In other words, this trick doesn't apply just to
sudo
:sudo !!
)time !!
)env A=b B=z !!
)!!
)History expansion (also known as history substitution) is just a shell feature to make repeating previous commands easier (with less keystrokes). Check your shell man page for
history expansion
. It describes many more tricks and short-cuts you can do with history for example:You may refer to previous commands by number:
You may refer to individual words in previous commands:
You can also search before repeating:
You can search the history and replace something by something else:
And much more, since you can combine command selection, arg-selection, search and replace independently.
The man page of your shell (in this case
man bash
) is your friend.I'll just add an alternative: as short as typing
sudo !!
and more flexible:It's exactly the same number of keystrokes (I count "ctrl+A" as one...), but adding "up arrow" you can do it on whichever command is in your history.
There are a few ways to do this
Simply enter the command again adding
sudo
before the commandPress Up arrow to get the last command and put
sudo
in front of it.Enter
sudo !!
The
!!
expands to the last entered command. You can do similar things with other things with the command line history see hereI use zsh instead of bash and have this in my
~/.zshrc
, so pressing Alt+S insertssudo
at the beginning of the command line:Unfortunately, I couldn't track down a way to do the same thing in bash.
If you want to do it in an alias, you have to use
alias redo='sudo $(history -p !!)'
for some reason.The way I prefer it:
But it might be easier to just do "sudo !!", it's up to you.
If you do not have permission to be root with sudo or sudo program did not install on system.