Bash – How to get sudo commands to use the settings in /root/.bashrc

bashdebiansudo

I have customised .bashrc with a number of alias, specifically ll and export LS_OPTIONS='--color=auto'

Unfortunately this does not work when used with sudo, so I also modified /root/.bashrc, but this seems to have made no difference.

sudo env shows HOME=/root and SHELL=/bin/bash

How can I get sudo commands to use the settings in /root/.bashrc?

I understand that this happens only when bash is executed interactively, so I am open to any other suggestions as to how to customise.

Best Answer

sudo runs an executable, not a shell command. So it doesn't know about aliases. If you run sudo ls, that's like sudo /bin/ls, it doesn't use any ls alias that you may have.

You can cause sudo ls to expand the alias by putting the following in your .bashrc:

alias sudo='sudo '

Note the trailing space — that tells the shell to continue alias expansion with the word that comes after sudo. Beware that expanding aliases after sudo may not always be a good idea, it depends what kinds of aliases you have.

Furthermore sudo removes most variables from the environment. This won't affect an alias like alias ls='ls $LS_OPTIONS', because that's a shell variable used by the shell while it's expanding the command (and exporting it from .bashrc serves no purpose). But it would affect variables that are used by the command, such as LS_COLORS. You can configure sudo to keep certain environment variables by editing its configuration: run visudo and add the line

Defaults env_keep += "LS_COLORS"

With these settings, sudo ll will give the colors you're used to.

Alternatively, you can run a root shell with sudo -s. This shell will load its configuration file (~/.bashrc for bash). Depending on how sudo is configured, this may keep HOME set to your home directory, or change it to /root. You can force the home directory to be set to root's with sudo -Hs; conversely, to keep the original home directory, run sudo env HOME="$HOME" bash.