Bash – ssh user@IP sh missed environment variables

bashenvironment-variablesprofilessh

I use an approach

ssh user@IP sh [runme.sh]

to execute script remotely, this works fine. But I got one problem, that is in runme.sh, I can't get any envirnoment variables which are defined in ~/.bashrc. If I launch the script locally, everything goes fine, but how can I get those environment configurations with ssh command?

One workable approach is to add one line

. ~/.bashrc

in every runme.sh in the very beginning, but in this way, I need to modify a lot of "runme.sh" files on clients. Is there a better idea ?

Best Answer

You shouldn't have environment variable definitions in ~/.bashrc, that file is for configurations for bash when running interactively (aliases, prompts, that kind of stuff). The place for environment variables is ~/.profile; it's read when you start an interactive session in text mode, and on many systems also in graphics mode. See this answer for more details.

To run a bash shell that sets your environment variables as usual for the remote machine, you can do

ssh user@IP bash --login runme.sh

For other shells, make them read your .profile (and perhaps /etc/profile as well):

ssh user@IP '. /etc/profile; . ~/.profile; exec runme.sh'

If you want to copy environment variables from your local session over ssh, that's possible but usually disabled on the server side. Read this answer for more details.

Related Question