Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have my custom Vim files in ~/.vim and settings in ~/.vimrc. However, sometimes I have to edit some files in /etc and such.
If I start Vim like this:

$ sudo vim /etc/rc.conf

I lose my config since Vim uses its default one. So: how can I run Vim with root privileges to edit files without losing my user's settings (which are in my home directory)?
I have tried:

$ su username -c "vim /usr/lib/python2.7/setuptools/dist.py"

but Bash gives me Permission denied. However, the above command works for example for: /etc/acpi/handler.sh. Why is that?

Note: username is not root.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

Instead of sudo vim /etc/rc.conf use sudoedit /etc/rc.conf or sudo -e /etc/rc.conf. You may need to set the EDITOR environment variable to vim. This will run vim itself as the normal user, using your normal configuration, on a copy of the file which it will copy back when you exit.

share|improve this answer
    
Nice solution! I'll check this out as well. –  rubik Aug 30 '12 at 13:25
    
I tried sudoedit /etc/rc.conf and sudo -e /etc/rc.conf and it opens vim, but my ~/.vimrc doesn't get loaded. What I am doing wrong? –  apparat Aug 30 '12 at 18:45
    
@apparat Try export EDITOR=vim first - it may be trying to run vi, which I don't know if it loads vimrc even when it is vim. –  Random832 Aug 31 '12 at 1:52
    
Well, I think this is the best answer. Thank you both. –  rubik Aug 31 '12 at 13:04
    
@Random832 export EDITOR=vim worked. I thought vi isn't installed on my system and is only a symlink to vim. Thanks –  apparat Sep 17 '12 at 7:47

You can use -u to tell vim which rc file to load. e.g.

sudo vim -u ~user/.vimrc /etc/rc.conf

if typing that every time you need to do it is tedious, make an alias:

alias sudovim='sudo vim -u ~user/.vimrc'

Note that vim -u may cause plugins or called rc files to fail if they load other files relative to $HOME - $HOME is now root's home dir, not the user's. This can be solved with e.g. symlinks in root's home dir or by hard-coding absolute paths.

share|improve this answer
    
That's great, thank you. I solved like this: alias svim="HOME=/home/user && sudo vim -u $HOME/.vimrc". –  rubik Aug 30 '12 at 10:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.