ssh user@IP sh <command> missed environment variables

9,850

Solution 1

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.

Solution 2

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.

Share:
9,850

Related videos on Youtube

Weiwei Yang
Author by

Weiwei Yang

Updated on September 18, 2022

Comments

  • Weiwei Yang
    Weiwei Yang over 1 year

    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 ?

  • Weiwei Yang
    Weiwei Yang about 13 years
    There're mutiple palces we can set environment variables, if you set it in /etc/profile, I'm sure it works. Thank you Andy.
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' about 13 years
    @Yang: When you run that first command, runme.sh is executed on the local machine. Your problem may be that .bashrc is exiting early, in which case the fix is to not define environment variables there but in .profile.