1

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?

1
  • You ran a non-interactive shell. The first thing that the default .bashrc checks is if it is an interactive shell, and if not, quits. Your modification to .bashrctherefore has no effect on a non-interactive shell.
    – muru
    Aug 3, 2015 at 17:51

1 Answer 1

3

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 :

case $- in
    *i*) ;;
      *) return;;
esac

This means check the shell options by $-, if the shell is not interactive (no i flag), exit from ~/.bashrc file.

So as you are spawning a non-interactive shell via bash -c, the PATH you have set at the end won't be read.

You have few options :

  • Use the -i option of bash so that bash behaves as an interactive shell and reads the ~/.bashrc file :

    /usr/bin/sudo -H -u <user> /bin/bash -i -c '<command>'
    
  • As you were using the -l option which tells bash to behave as a login shell, you can put the PATH in ~/.profile so that it will be source-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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .