Why does my .bashrc get read when I run noninteractive commands over ssh

4

I've prepended each of my bash config files (~/.bashrc,~/.bash_profile,~/.profile) with echo NAME_OF_FILE, i.e. I get '.bashrc' when I source in ~/.bashrc.

What baffles me is why I get and indication that ~/.bashrc gets included when I run a command over ssh. E.g., if I do:

ssh localhost echo hi

I get

.bashrc
hi

Why is getting ~/.bashrc sourced in in this context? Shouldn't it NOT get sourced in since this should run an non-interactive bash session?

Indeed, ssh localhost tty gets me a 'not a tty' (preceded by '.bashrc' indicating that ~/.bashrc gets sourced in nonetheless).

I've grepped all my config files for commands sourcing in ~/.bashrc explicitly, and there are none that explain it.

(I only have tty -s && shopt -q login_shell && [[ -r ~/.bashrc ]] && . ~/.bashrc in my .bash_profile so that I get '.bashrc' even in interactive login shells, but this doesn't explain the ssh issue—I can comment it out and I still get the same behavior with the above ssh examples)

How can I debug this?

PSkocik

Posted 2014-05-07T10:39:49.740

Reputation: 1 182

Could it be your BASH_ENV variable? – m4573r – 2014-05-07T11:22:44.377

Answers

8

From bash man page:

Bash attempts to determine when it is being run with its standard input
connected to a a network  con‐nection,  as  if  by  the remote shell daemon,
usually rshd, or the secure shell daemon sshd.  If bash
determines it is being run in this fashion, it reads and executes commands
from  ~/.bashrc,  if  that file  exists and is readable.

I.e. ~/.bashrc will get run when you invoke it via ssh, regardless of whether you have a tty or not.

If you only want your .bashrc to run when you are interactive, try this at the top:

# If not running interactively, don't do anything
[[ "$-" != *i* ]] && return

If that doesn't work, try this:

[ -z "$PS1" ] && return

Lqueryvg

Posted 2014-05-07T10:39:49.740

Reputation: 558

Both didn't work on CentOS 7. – yildizabdullah – 2018-05-02T14:19:52.443

@yildizabdullah you need to debug. Start by adding an echo or set -x at the top and see if your .bashrc is even being called. Then examine the values of those variables. – Lqueryvg – 2018-05-03T08:13:11.067

@Lqueryvg I added echo command at the top and it ran. That is, .bashrc was called. – yildizabdullah – 2018-05-03T09:27:04.487

Do a set and an env - try to work out what $- and $PS1 are set to. (I'm starting to wonder if you are really in bash.). Type bash to get a sub-shell - so that you definitely know you are in a bash - and look at the values there. – Lqueryvg – 2018-05-03T09:55:08.277

1The manual page is a bit unclear, as most remote connection tools – rshd, telnetd, sshd – attach bash's stdin/stdout to a pseudoterminal, not directly to the network socket (which would actually be impossible for sshd). Will check the source code later. – user1686 – 2014-05-07T14:11:51.023