Why do I not have syntax highlighting when I sudo vi <filename>?

Larks answer is probably the most likely. You may not wish to change your root accounts vi to vim permanently as if your resources are low vi is almost guaranteed to always work, I'm not so sure about vim.

You are probably using (color)

/usr/bin/vim 

under your normal user and

/bin/vi

under sudo or root. You can check by using:

which vi

once under your normal user and the other via sudo

sudo which vi

Do a

man which 

if you need more details


On a RHEL system, /bin/vi is typically a minimal version of vim, without any syntax highlighting support. /usr/bin/vim is the full-featured editor. It is very likely that in your user environment, vi is an alias for vim. Try this:

sudo vim /some/file

Do you get syntax highlighting now?


Your vi is probably /bin/vi from package vim-minimal which does not support syntax highlighting. sudo vi launches /bin/vi for you.

Bash only does alias expansion on the first word in your command line, so in:

sudo vi

vi is not substituted to vim even if you have that alias defined.

The solution is define another alias (for the user invoking sudo):

alias sudo='sudo '

Note the space after the second sudo.

Using this sudo, bash will do alias expansion for vi in sudo vi. In the alias section of Bash doc it says:

If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.

After you enter your command, You can press Ctrl+Alt+E in bash to see the expansion result.

Credits:

https://bbs.archlinux.org/viewtopic.php?id=36796

http://www.shellperson.net/using-sudo-with-an-alias


Simply aliasing vi in /root/.bashrc will not work.

It may also be noted that vi is not aliased for root on some distros in /etc/profile.d/vim.sh:

if [ -n "$BASH_VERSION" -o -n "$KSH_VERSION" -o -n "$ZSH_VERSION" ]; then
  [ -x /usr/bin/id ] || return
  ID=`/usr/bin/id -u`
  [ -n "$ID" -a "$ID" -le 200 ] && return
  # for bash and zsh, only if no alias is already set
  alias vi >/dev/null 2>&1 || alias vi=vim
fi

Changing this will not solve the problem either.