Use sudo with .vimrc

Use sudoedit instead of sudo vim. You should be doing that anyway. Make sure your EDITOR environment variable is set to vim (probably already is, or vim is the default; you can set it in your .profile analog if need be).


As shown here, you can use the following:

sudo -E vim README.txt

From the man page:

-E    The -E (preserve environment) option indicates to the security policy that the user wishes to preserve their existing environment variables.  The
  security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment.

The accepted answer is the most secure. But this one is more flexible as I can use sudo -E operation with any operation, I don't have to configure anything else beforehand.


/root/.vimrc is the working directory of sudo vim.

You need copy your .vimrc file from /home/ec2-user/.vimrc to /root/.vimrc


The presented solutions in the other responses work but are not very practical, as you have to enter you password every time you want to edit a file.

I usually have a tmux session open within which I am rooted via sudo su, so I enter my password once at the beginning of the session and can then work for hours without having to enter it again.

I worked around the issue presented here by creating the following symbolic links : sudo su ln -s /home/MY-USER-NAME/.vimrc .vimrc ln -s /home/MY-USER-NAME/.vim .vim

You might need to remove the /root/.vim/ directory first.

I hope this helps