Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sudo with .vimrc

Tags:

vim

centos

I'm using CentOS and created a .vimrc file in my /home directory. I tested it out by creating a txt file and yes, that worked fine. Now, I have my project files in my /srv directory with SELinux turned on. I tried opening a file: vim README.txt and yes, my .vimrc settings are still being applied.

Now, since I'm in the /srv directory, simply doing vim means that my file is read only. So, I do sudo vim README.txt in order to be able to edit files. Now, the problem lies that once I do sudo, none of my .vimrc settings are applied. I tried creating a copy of .vimrc in the /srv folder but that didn't work either.

How do I apply .vimrc settings while using sudo?

like image 357
noblerare Avatar asked Jan 31 '14 19:01

noblerare


People also ask

How do I access .vimrc files?

The global or system-wide vim configuration file is generally located under the /etc/vim/vimrc . This configuration file is applied to all users and when Vim is started this configuration file is read and Vim is configured according to this file contents.

How do I open a .vimrc file in Terminal?

In the terminal, type vi . vimrc . This will create an empty vimrc system file which you want to use. In the file, type set number , and then hit Esc on the keyboard and type in :wq .

How do I save a file in Sudo?

You can use the combination of sudo command (assuming that sudo is configured for your account) to save a file without creating a third file in /tmp. This is useful to write a privileged file with sudo command. For example saving a read-only file edited in vim and vi is possible with this trick.


2 Answers

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).

like image 176
Explosion Pills Avatar answered Nov 01 '22 22:11

Explosion Pills


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.

like image 39
leetNightshade Avatar answered Nov 01 '22 21:11

leetNightshade