ZSH Tip of the Day: #2

How many times have you forgotten to use sudo when executing commands? Countless, I'm sure. One trick is to simply write sudo !!, since !! is replaced with the full contents of the previously entered command. Sure beats re-entering the entire thing. But we can do better - three key strokes should be enough. Here's how I do it:

# Prefix the previous line with "sudo " then execute it
rerun-with-sudo () {
  LBUFFER="sudo !!"
  zle accept-line
}
zle -N rerun-with-sudo

bindkey '\C-x\C-x' rerun-with-sudo

I think this small function showcases how nice zle is. LBUFFER is basically a variable which contains the contents of the prompt. Since this function assigns to LBUFFER, it overwrites anything already there (if anything) with sudo !!. zle accept-line is equivalent to hitting enter. Finally I bind the function to ^x^x - which now can be used to quickly rerun commands with sudo.

blog comments powered by Disqus