Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Execute last command as superuser UNIX
Isn't it annoying when you try to do something, only to find out it requires superuser privs? And you have to retype it with "sudo"? No more!

An easy trick (in tcsh) to perform the last command as sudo is:
sudo !!
This uses the powerful "History substitution" feature of tcsh. For more history substitution tricks: "man tcsh" and type "/History"
    •    
  • Currently 4.00 / 5
  You rated: 4 / 5 (2 votes cast)
 
[4,592 views]  

Execute last command as superuser | 3 comments | Create New Account
Click here to return to the 'Execute last command as superuser' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Tim Toady
Authored by: babbage on Jun 12, '02 09:10:21AM
This is indeed a useful trick but ...you can just hit the up key [roll back to previous command(s)], jump to the beginning of the line [Emacs keybindings: ctrl+A for beginning, ctrl+E for end, etc], type "sudo " and hit enter. The big timesaver there is the [UP] [ctrl+A] combo: you can scoll back any number of commands, add the sudo prefix, and while you're at it you can make any minor edits to the command too.

That said, this isn't all that different from the original trick. Both of them work out to 5+3 keystrokes ('sudo " plus either [shift 1 1] or [up control A]). The scrolling through history trick I describe makes it easy to see what you're [re]executing, but the exclamation points hack is actually much more subtle than this. I personally haven't really pushed it, but it's possible to use your command history interactively -- such as repeating the last "grep" command, even if it was some time yesterday.

The tcsh man page goes over this, but I also recommend taking a look at O'Reilly's Unix Power Tools. It has a big section on the different shells & how they can be leveraged. There's also the csh/tcsh book, but the Power Tools one covers *everything*, so if you get stuck on a Linux machine and have to use Bash you'll be able to look up the trickery there too :-)

[ Reply to This | # ]

naw
Authored by: bhines on Jun 12, '02 10:29:07PM

control-a is pretty hard to type, especially now that the control key is in the corner. sudo !! is also easier mentally, in that you don't have to carefully hit the up-arrow and make sure the command is the right one. (that you didn't hit it too many times)



[ Reply to This | # ]
more on history
Authored by: iroot on Jun 15, '02 03:50:54PM

and just because it may not be obvious, you can use the history command; then type !number, where number = the command number in your history output. For example: !59.



[ Reply to This | # ]