Friday, January 3, 2014: please — repeat last command as root.

Today I’d like to introduce you to this recipe you can put in your .bashrc:

alias please='sudo bash -c "$(history -p !!)"'

You probably have had these moments when you are trying to run a command only to find out that you are not root:

echo 127.0.0.1 dev.my.test.app.com >> /etc/hosts
-bash: /etc/hosts: Permission denied

With this alias, you can just re-run the command using

▹ please

and it will re-run the command as root. Note that it also works with redirections!

Handles Arguments Correctly

To see if this recipe works well with complex commands, consider this example:

▹ ruby -e 'p [ARGV, `whoami`.strip]' a 'b c' "d e" f `whoami`
[["a", "b c", "d e", "f", "dttvb"], "dttvb"]

▹ please
[["a", "b c", "d e", "f", "root"], "root"]

As you can see, the whole command is run as if it’s being typed again, but in the root shell.