Use non-root user configuration for root account

command lineconfigurationsusudo

When I work with the terminal and use su or sudo to execute a command with the root user's permissions, is it possible to apply the configuration of my "non-root user" (from which I am invoking su or sudo) stored in this user's home directory?

For instance, consider that (being logged on as a non-root user) I would like to edit the configuration file /etc/some_file using vim and that my vim configuration file is located at /home/myuser/.vimrc. Firing up the command line and typing sudo vim /etc/some_file, I would want "my" beautiful and well-configured vim to show up. But what I get is an ugly vim with the default configuration, no plugins etc.

Can I make su or sudo use my user's configuration files instead of the root user's files located at /root?

Best Answer

Use sudo -E to preserve your environment:

$ export FOO=1
$ sudo -E env | grep FOO
FOO=1

That will preserve $HOME and any other environment variables you had, so the same configuration files you started with will be accessed by the programs running as root.

You can update sudoers to disable the env_reset setting, which clears out all environment variables and is generally enabled by default. You may have to enable the ability to use sudo -E at all in there as well. There are a few other sudoers settings that might be relevant: env_keep, which lets you specify specific variables to keep by default, and env_remove, which declares variables to delete always. You can use sudo sudo -V to see which variables are/are not preserved.

An alternative, if you can't modify sudoers, is to provide your environment explicitly:

sudo env HOME=$HOME command here

You can make a shell alias to do that automatically so you don't have to type it in.

Note that doing this (either way) can have potentially unwanted side effects: if the program you run tries to make files in your home directory, for example, those files will be created as root and your ordinary user won't be able to write to them.

For the specific case of vim, you could also put your .vimrc as the system-wide /etc/vimrc if you're the only user of this system.

Related Question