Start Vim as my user with root privileges

10,631

Solution 1

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.

Solution 2

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.

Solution 3

sudo vim -S /home/user/.vimrc /etc/rc.conf

This is equivalent to:

sudo vim /etc/rc.conf + :source /home/user/.vimrc

and can be aliased as well:

alias svim='sudo vim -S /home/user/.vimrc'

Share:
10,631

Related videos on Youtube

rubik
Author by

rubik

Updated on September 18, 2022

Comments

  • rubik
    rubik over 1 year

    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.

  • rubik
    rubik over 11 years
    Nice solution! I'll check this out as well.
  • apparat
    apparat over 11 years
    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?
  • Random832
    Random832 over 11 years
    @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.
  • rubik
    rubik over 11 years
    Well, I think this is the best answer. Thank you both.
  • apparat
    apparat over 11 years
    @Random832 export EDITOR=vim worked. I thought vi isn't installed on my system and is only a symlink to vim. Thanks