Bash – SSH remote command no reading all environment variables

bashgitssh

I have declared some "PATH" variables in the ".bashrc" file of a remote machine. When I login to the remote machine, all these "PATH" variables work fine. But when I do a "ssh user@remote env", the "PATH"s declared in the ".bashrc" are not read. How can I fix this?

This is the ".bash_profile" in the home directory on the remote machine:

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs
PATH=$PATH:$HOME/bin:

export PATH

This is the ".bashrc" in the home directory on the remote machine:

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

# PATH
export PATH=$HOME/git-1.8/bin/:$PATH

And this is the present output of the command "ssh user@remote env" from my local machine:

SHELL=/bin/bash
SSH_CLIENT=NNNNNNNNNNNNNNN
USER=XXXXXXXXX
MAIL=/var/mail/XXXXXXXX
PATH=/usr/local/bin:/bin:/usr/bin:/usr/local/openssh/bin
PWD=/volume2/home/hp120242/XXXXXXXXX
SHLVL=1
HOME=/home/hp120242/XXXXXXXXXX
LOGNAME=XXXXXXXXXXXXX
SSH_CONNECTION=NNNNNNNNNNNNNNNNNNN
LC_CTYPE=en_US.UTF-8
_=/bin/env

I don't have root permissions on the remote.

Best Answer

On my box, stuffing export HI=THERE into an otherwise empty ~/.bashrc shows this output when ssh is used to contact the box for an env listing:

$ ssh $host /usr/bin/env 2>/dev/null | grep HI
HI=THERE

My ~/.bashrc takes the approach of checking for a user-specific environment variable and then, if it's missing, does the equivalent of:

. ~/.profile   # load in (Bourne-shell syntax) baseline environment variables

Hence, my ssh commands - even though bash starts up as though it's a subshell (.bashrc only) - still get the environment variables I normally expect for non-interactive shells. I t seem to remember doing this explicitly for SSH many years ago.

You could have your ~/.profile set some variable, say ENVGOOD=true, then have this in your ~/.bashrc:

[ -z "$ENVGOOD" ] && . ~/.profile  # sets ENVGOOD=true

or create a ~/.ssh/environment. Note that this latter will only work if PermitUserEnvironment = true in the /etc/ssh/sshd_config is set, which is NOT the default (and assuredly why my setup doesn't rely on it).

Related Question