Command Line – Environment Variables When Running with ‘sudo’

command lineenvironment-variablessudo

As example to my question, my ~/.bashrc file contains this lines:

export LD_LIBRARY_PATH=/opt/intel/mkl/lib/ia32:$LD_LIBRARY_PATH
export LD_PRELOAD=/opt/intel/mkl/lib/ia32/libmkl_core.so

so that Numpy (Python) could find libraries that it needs to run, as it's build with MKL and Intel compilers. This workflow isn't the best, but that's another story.

My question is how can I pass arbitrary variables (like those in ~/.bashrc) when I run program with 'sudo' (but not root)?

Currently, if I run:

sudo python -c "import numpy"

I get an error:

ImportError: libimf.so: cannot open shared object file: No such file or directory*

Some suggestions as sudo -i or sudo -E does not change anything here.


Edit:

I can't answer my question (not enough points 😀 ) but I'll comment here, in a hope that there are other Linux newbies wondering about sudo traps.

[Only temporarily!] This works for me (~/.bashrc):

alias sudo='sudo env PATH=$PATH VAR1=SOME_VALUE VAR2=SOME_VALUE...'

Best Answer

Environment variables can be simply passed after sudo in form ENV=VALUE and thay'll be accepted by followed command. It's not known to me if there are restrictions to this usage, so my example problem can be solved with:

sudo LD_LIBRARY_PATH=/opt/intel/mkl/lib/ia32:$LD_LIBRARY_PATH LD_PRELOAD=/opt/intel/mkl/lib/ia32/libmkl_core.so python -c "import numpy"
Related Question