3

I am trying to make a working example for logrotate, and to help me through this I figured it was a good idea to turn stderr to red.

Through some reading, I came upon stderred, which I meant to adopt. I downloaded it, make'd it and it works nicely for the user.

The red formatting however is lost when the command is summoned through sudo. Specifically, red formatting is visible with this command:

$ /usr/games/cowsay -f fudge Yo
cowsay: Could not find fudge cowfile!

but not with this command:

$ sudo /usr/games/cowsay -f fudge Yo
cowsay: Could not find fudge cowfile!

I have tried editing /root/.bashrc to contain:

export LD_PRELOAD="/home/user/path/to/stderred/build/libstderred.so${LD_PRELOAD:+:$LD_PRELOAD}"

but that apparently does not make it work. What am I missing?

Tfb9
  • 681

1 Answers1

3

This is because sudo command runs command in its own subshell, started by root. This means that your ~/.bashrc file is ignored. It also means that any environment variables defined in the parent shell (such as the LD_PRELOAD you are setting in ~/.bashrc) are not passed to the sudo shell. This is explained in man sudoers:

By default, the env_reset option is enabled. This causes commands to be executed with a new, minimal environment. On AIX (and Linux systems without PAM), the environment is initialized with the contents of the /etc/environment file. The new environment contains the TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER, USERNAME and SUDO_* variables in addition to variables from the invoking process permitted by the env_check and env_keep options. This is effectively a whitelist for environment variables.

I couldn't get the env_keep option to work here, I don't know why. The best way I could find of passing the variable to sudo is to create a file (for example /path/to/foo) with this line:

LD_PRELOAD="/home/terdon/Setups/stderred/build/libstderred.so"

Then, run sudo visudo and add this line:

Defaults        env_file="/path/to/foo"

That will cause sudo to read /path/to/foo and add any variable definitions there to its environment.

terdon
  • 104,119