Rerun previous command under sudo

Solution 1:

Add to your .zshrc:

alias please='sudo $(fc -ln -1)'

Solution 2:

You cannot use !! in a shell script, as you cannot access the parent shell in a child shell. Though I recommend using sudo !!, if you really want to make a BASH script, you would have to use .bash_history, like so:

#!/bin/bash
sudo `cat $HOME/.bash_history | tail -n1`

It is definitely NOT a perfect solution, but it should do the trick. If you are using ZSH, this will not work, as ZSH does not output to .bash_history (of my knowledge). UPDATE: Here is a version that should work with ZSH:

#!/usr/bin/zsh
. $HOME/.zshrc
sudo `cat \`readlink -f $HISTFILE\` | tail -n1`

Hope this helps!

If you don't understand the script, it simply runs the last command entered in BASH with sudo.