Take the 2-minute tour ×

Usually, for some commands such as apt-get install xxx, I forget to add sudo first, then I need to retype it. What I want is in such cases, I just type a simple command, for example resudo. It will sudo my last command sudo apt-get install xxx. Is it possible in bash?

share|improve this question
For apt-* in particular, there's wajig. –  delnan Feb 19 '11 at 14:55
add comment

migrated from stackoverflow.com Feb 19 '11 at 15:23

This question came from our site for professional and enthusiast programmers.

1 Answer

up vote 18 down vote accepted

You could just use bash's !!: it is a shortcut to rerun the last command.

sudo !!

Anyway bash offers many shortcuts for anything, you could just press the up arrow (in order to get back the last typed line), then press ^A or Home and add sudo there.

Here a useful bash cheatsheet

share|improve this answer
Thanks, it works great. But still another question, it seems that !! is not recognized in bash script, why? for example, i want to get the last command last_command=$(!!), it doesn't work. –  Todd Feb 19 '11 at 15:01
@Todd: $() evals a command, replaces it with the result of the command. You just need to do: last_command=!!, otherwise if !! was for example echo Hello, last_command=$(!!) will be expanded to last_command=hello. –  peoro Feb 19 '11 at 15:03
@peoro: please test in your bash, last_command=$(!!) causes interpretation error. Seems !! is just not recognized. –  Todd Feb 19 '11 at 15:08
@Todd: history expansion is (generally) disabled inside scripts because it doesn't make any sense. Remember that scripts run in subshells, so if you could use !! in a script it'd expand to the previous line of that script, not the last thing the user running the script did. If you're trying to make a shorthand for sudo !!, see my answer here for how to make a shell alias to do it. –  Gordon Davisson Feb 19 '11 at 15:36
add comment

Your Answer


