My question is why do I lose environment information like $PATH
when running the following command:
/usr/bin/sudo -H -u <user> /bin/bash -l -c '<command>'
I'm trying to add the /mnt/anaconda
path to this command. So what I tried doing was to add in the ~/.bashrc
for the user:
export PATH="/mnt/anaconda/bin:$PATH"
Also configured in visudo
Defaults env_keep = "PATH"
But none of those changes took effect, do you guys have any suggestions?
Best Answer
When you run a command in
bash
via-c
option, a non-interactive shell is spawned. The~/.bashrc
file is sourced for non-login interactive shells (and also for login interactive shells, sourced from~/.profile
). The main point is interactivity.The
~/.bashrc
file has the following snippet at the start :This means check the shell options by
$-
, if the shell is not interactive (noi
flag), exit from~/.bashrc
file.So as you are spawning a non-interactive shell via
bash -c
, thePATH
you have set at the end won't be read.You have few options :
Use the
-i
option ofbash
so thatbash
behaves as an interactive shell and reads the~/.bashrc
file :As you were using the
-l
option which tellsbash
to behave as a login shell, you can put thePATH
in~/.profile
so that it will besource
-ed. Note that this might not a good option considering your need.Another very very bad option would be to put
PATH
at the very start of the~/.bashrc
file, before the interactivity check snippet.