4

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?

Alvin Row
  • 603
  • 6
  • 10
Dagang
  • 197
  • 6
  • [For `apt-*` in particular, there's `wajig`.](http://unix.stackexchange.com/questions/767/what-is-the-real-difference-between-apt-get-and-aptitude-how-about-wajig) –  Feb 19 '11 at 14:55

1 Answers1

19

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

peoro
  • 1,151
  • 9
  • 18
  • 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. –  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. –  Feb 19 '11 at 15:08
  • 4
    @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](http://superuser.com/questions/240180/creating-an-alias-containing-bash-history-expansion/240193#240193) for how to make a shell alias to do it. – Gordon Davisson Feb 19 '11 at 15:36