Run Last Command as Sudo Quickly

In this post I'll show to how you can easily prepend sudo to a command

Posted by Karan on August 03, 2018   862 views

Forgot to add sudo? Don't panic, you won't need to toggle previous command with arrow keys and edit, instead you can use !! in shell provided that the shell you are using has csh-like history substitution(bash, zsh, tsh). To run previous command you can try following command in shell

sudo !!

There are many options related with ! 

Specifier Description
!! Repeat previous command
!n Repeat command n
!-n Repeat n-th-to-last command
!str Repeat last command beginning with str
!?str? Repeat last command containing str
!# Repeat the current command line typed so far

Note that !! or !-n etc. will not auto-expand until you execute them, you can use magic space to bind space key to expand them, to do that:

bindkey " " magic-space

above command will work for tcsh, zsh, if you are using bash then run following command instead of above command

bind Space:magic-space

you may want to add above command to ~/.shellnamerc file like zshrc, bashrc.

If you are using oh-my-zsh then you can add sudo to plugins in .zshrc file and just press escape key twice to insert sudo before a command.

 


blog comments powered by Disqus