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 ?


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.

| improve this answer | |

How about this:

ssh user@IP -- '. ~/.bashrc; sh runme.sh'

You should probably be a bit careful about the distinction between sh and bash. If you have fancy customizations in .bashrc, and sh is something like dash, then this might fail.

| improve this answer | |

How about sourcing the /etc/profile on ssh command?

ssh user@host "source /etc/profile; sh runme.sh"

Adopted from an answer on this question

| improve this answer | |
  • There're mutiple palces we can set environment variables, if you set it in /etc/profile, I'm sure it works. Thank you Andy. – Weiwei Yang Apr 28 '11 at 7:56
# If not running interactively, don't do anything
[ -z "$PS1" ] && return

Typically ~/.bashrc will start with some form of the previous code. When you execute a command directly with ssh, bash will not be running interactively so you need to make sure that the environment variables you want to set are before any such line.

| improve this answer | |

On the target system, is sh actually bash? It very well may not be, which is one potential reason for your .bashrc not being read automatically.

Does running bash runme.sh work? If so, that's your problem.

Also as someone pointed out already, if you have anything that detects whether your shell is running interactively in your .bashrc, your variables must be set above this code.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.