Run the Last Executed Command as Root with sudo !!

Jul 20, 2010 - 1 Comment

Mac Terminal icon

Have you ever tried to run a command line tool to discover that you don’t have the necessary privileges to use it? Or perhaps the command itself actually requires root access to run at all? You’ll typically experience this with a ‘permission denied’ type of error message in terminal. Rather then type out the entire command string again, or hit the up arrow and move the cursor over to precede the command with sudo, you can use an awesome trick which re-runs the last executed command with sudo privileges. Best of all, this great re-run last command as root trick works in MacOS / Mac OS X and Linux.

OK, by the headline alone you’re probably thinking this is just a bit of hyperbole because of the exclamation points, but I swear I’m not just super excited about the sudo command (though this command is really great!)… no, instead the exclamation points are actually part of the usage of the sudo tool in this regard.

How to Re-Run Last Executed Command as Root User

If you want to quickly run the last command executed but as the root superuser, simply type the following:

sudo !!

Yes, that’s “sudo” followed by a space and two exclamation points.

This will instantly run the previously run command but with sudo prefix, which typically means you’ll need to enter an admin password to complete the sequence.

An example of this would be if you’re trying to edit the hosts file or another system file that you need system privileges for. Instead of re-entering the entire command string preceded with sudo, just type sudo !! and the previous command (!!) will be run under sudo.

For example, let’s say you were trying to modify the users host file:

nano /etc/hosts

But you can’t save or edit the file because of lack of appropriate user credentials, right? No sweat, rather than typing out the full ‘sudo nano /etc/hosts’ command sequence again, just type the following:

sudo !!

This takes the last command (in this case, nano /etc/hosts) and prefixes it with sudo automatically, becoming the complete ‘sudo nano /etc/hosts’

This works with literally every command line tool and command execution, so try it out, it’s pretty awesome.

As mentioned earlier, this trick works in the command line of MacOS and Linux, and probably many other unix based operating systems as well.


Related articles:

Posted by: Bill Ellis in Command Line, Tips & Tricks

One Comment

» Comments RSS Feed

  1. pederast says:

    !! is not related to sudo. It’s a bash event designator that refers to the last command. !-{n} would refer to the command issued n commands ago. !! is equal to !-1.

Leave a Reply


Shop on and help support OSXDaily!

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates

Tips & Tricks


iPhone / iPad



Shop on Amazon to help support this site