Shellisms: Automagically sudo when editing files

I get irritated to no end when I start editing a file in Vim, only to realize I don’t have write permissions to that file. I wrote this little bash function to address that a few years ago. It checks if I have write permissions to the file I am trying to open, and runs the editor in sudo if I do not. It could be cleaner, but it works. Simply toss it into your .bashrc, and enjoy.

if [ `which vim` ]; then
        VI=`which vim`
else
        VI=`which vi`
fi

sudowarn () {
        if [ "`id -u`" -eq 0 ]; then
                "$@"
                return
        fi

        echo "RUNNING AS ROOT"
        echo "RUNNING AS ROOT"
        echo "RUNNING AS ROOT"
        echo "RUNNING AS ROOT"
        echo "RUNNING AS ROOT"
        sleep 1
        sudo "$@"
}

vi () {
        if [ ! -d "$1" ] && [ ! -f "$1" ]; then
                $VI "$@";
                return
        fi

        if [ -w "$1" ]; then
                $VI "$@";
        else
                sudowarn $VI "$@";
        fi
}
Share and Enjoy:
  • StumbleUpon
  • Facebook
  • Twitter
  • Reddit
Shellisms: Automagically sudo when editing files

Leave a Reply

Your email address will not be published.