Why is SSH not invoking .bash_profile?

Solution 1:

Do you have a .bashrc file set? It could be damaged or corrupted or has something that causes the processing of .bashrc to choke and fail. And as a result, the doesn’t get to the point where it can cleanly digest/process .bash_profile.

As shown on this site, .bashrc loads before .bash_profile:

+----------------+-----------+-----------+------+
|                |Interactive|Interactive|Script|
|                |login      |non-login  |      |
+----------------+-----------+-----------+------+
|/etc/profile    |   A       |           |      |
+----------------+-----------+-----------+------+
|/etc/bash.bashrc|           |    A      |      |
+----------------+-----------+-----------+------+
|~/.bashrc       |           |    B      |      |
+----------------+-----------+-----------+------+
|~/.bash_profile |   B1      |           |      |
+----------------+-----------+-----------+------+
|~/.bash_login   |   B2      |           |      |
+----------------+-----------+-----------+------+
|~/.profile      |   B3      |           |      |
+----------------+-----------+-----------+------+
|BASH_ENV        |           |           |  A   |
+----------------+-----------+-----------+------+
|                |           |           |      |
+----------------+-----------+-----------+------+
|                |           |           |      |
+----------------+-----------+-----------+------+
|~/.bash_logout  |    C      |           |      |
+----------------+-----------+-----------+------+

I would recommend checking that .bashrc and maybe even temporarily renaming it something like .bashrc_off to disable it to test the theory before debugging any further.

Solution 2:

ssh with a command will NOT start a login shell. Thus bash_profile is not sourced.

See details here

Solution 3:

add -l may be an easy workaround, -l option makes bash act as a login shell, a login shell will execute .bash_profile.

ssh $host bash -l -c single_word_command

or

ssh $host bash -l -c '"commands with space"'

because $ sign needs escape, to echo $PATH some additional work is needed, something like

ssh $host bash -l -c "'echo \$PATH'"

the \ before $ prevent "local" shell to replace $PATH to real value, the ' in " is needed because outer " is removed after sending to "remote"

by the way ssh -v and bash -v is very helpful for debugging escape things like this