How to write a script to sudo the last command

4

1

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?

Dagang

Posted 2011-02-19T14:52:25.253

Reputation: 167

Question was closed 2014-07-04T17:58:26.187

For apt-* in particular, there's wajig. – None – 2011-02-19T14:55:19.770

Answers

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

Posted 2011-02-19T14:52:25.253

Reputation: 943

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. – None – 2011-02-19T15:01:24.363

@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 – 2011-02-19T15:03:44.747

@peoro: please test in your bash, last_command=$(!!) causes interpretation error. Seems !! is just not recognized. – None – 2011-02-19T15:08:41.587

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 for how to make a shell alias to do it.

– Gordon Davisson – 2011-02-19T15:36:51.487