2

Running Ubuntu 12.04.

I have a script that sets up the environment, its run by /etc/bash.bashrc. (It may be set to run by other shell profiles inits, I didn't actually set it up myself)

When I Ctr+Alt+T to open a terminal, the script runs once. But if I SSH into my machine from another box, the /etc/bash.bashrc init script runs, but then it also gets run again, and I'm not sure why.

Other users experience the same 'double' initialize. It's not necessarily a problem, but I would really like to isolate the issue for academic reasons.

I added an echo into /etc/bash.bashrc to let me know when it's executing. I see the echo the first time, but not the second time, leading me to believe something else is executing the script, I just can't figure out what it is. I checked ~/.profile, ~/.bashrc, and ~/etc/profile

I should emphasize that this behavior only happens when a user SSHes into the machine. I know there is some difference between interactive/login/non-login shells, but I'm not quite clear on the matter yet...

reas0n
  • 221
  • 1
  • 2
  • 12

1 Answers1

2

To figure out what's invoking that environment setup script, you need to add tracing commands in that script, not in the one place where you know it's used.

There's no portable way to report the stack of shell script inclusions. In bash, you can see that through the BASH_SOURCE variable. Dash keeps sourced scripts open while running them, so listing the open files should give you a good idea. Since bash is the default interactive shell and dash is the default scripting shell, this should cover most cases.

if [ -n "$BASH_SOURCE" ]; then
  eval 'echo "${BASH_SOURCE[@]}"'
else
  readlink /proc/$$/fd/[4-9] 2>/dev/null
fi

(${BASH_SOURCE[@]} is protected behind eval because it's a syntax error in sh.)


Note that .bashrc or /etc/bash.bashrc is the wrong place for environment variables. It's only run by interactive non-login instances of bash — in particular it isn't executed for SSH logins. If /etc/bash.bashrc is executed for an SSH login then it means that another script (typically ~/.bash_profile) sources it. The right place for site-specific environment variables is a script in /etc/profile.d/ or extra entries in /etc/environment.

Regarding login shells and interactive shells, see Difference between Login Shell and Non-Login Shell?

  • OK, so I should execute the env init script in profile.d. the bash.bashrc code also exports MATLAB/bin to $PATH after the init script (although they are not depndent on each other) . Is there a better place for that? – reas0n Jul 01 '16 at 14:51
  • 1
    @Elijah /etc/profile.d/somefile is the right place for that. – Gilles 'SO- stop being evil' Jul 01 '16 at 16:11