0

I have the following in my .bash_profile:

echo bash_profile
if [ -f $HOME/.bashrc ]; then
    echo Sourcing bashrc
    source $HOME/.bashrc
    echo Sourced bashrc
fi

My .bashrc file is quite long, but at the end I have an echo Path set statement and some exports.

When I execute sudo su - username I get the following output:

bash_profile
Sourcing bashrc
Path set
Sourced bashrc

However, when I execute sudo su - username -c '' I get this:

bash_profile
Sourcing bashrc
Sourced bashrc

Why is it that the source command stops working with the -c flag? I need the changes made to the PATH in .bashrc when executing a command with sudo su - username -c.

3
  • 1
    Perhaps your .bashrc is checking whether or not the shell is interactive (by looking at the shell options in special variable $- for example) and is not processing the rest of the file in the non-interactive case? Jan 21, 2020 at 1:47
  • @steeldriver Right on the money. If you add that as an answer I'll accept it.
    – Omegastick
    Jan 21, 2020 at 2:03
  • OK thanks - done Jan 21, 2020 at 2:15

1 Answer 1

2

The .bashrc file is really intended to be sourced in interactive shells - to allow it to be source in a non-interactive environment such as bash -c or su -c without error, it's not uncommon to add an "interactivity test" somewhere near the top of the file.

For example, the start of the Ubuntu default .bashrc file (copied from /etc/skel on account creation) looks like:

$ head /etc/skel/.bashrc
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

So, likely your .bashrc is successfully being sourced - but is returning before reaching the commands that modify your PATH.

You must log in to answer this question.

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