Keeping aliases with sudo (sort of)

I have an alias for vi that runs vim instead — simply:

alias vi='vim'

The problem was, aliases aren’t kept when running sudo (see man sudo and man sudoers).

So my natural tendency to write “sudo vi /etc/group” would end up calling vi, not vim — and I’d loose the syntax coloring I’ve fell in love with.

I’ve found some ugly work arounds over time, but after resetting my configuration after a reformat, I checked again and came across a beautiful alternative:

alias sudo='sudo '

Since the last character in the alias is a space, the next command is checked for alias expansion.

So now my

sudo vi /etc/group

expands to

sudo vim /etc/group

calling vim and my syntax coloring is restored.

Much thanks to for this one.

PS I say “sort of” because it will only work if your alias is the command immediately following sudo (which I expect most are).

Posted Saturday, July 3rd, 2010 under linux, tips and tricks.

One comment so far

  1. Amazing solution. Thanks so much.

Leave a Reply