7

I have two servers X(host) and Y(remote). A script abc.sh is saved on Y server. I am running abc.sh from server X using ssh command.

Script is running successfully but the commands which contain the environment variables(kept in /.bash_profile) of server Y are giving blank output.

When I am running abc.sh from server Y itself, all commands running successfully.

My question is how to include the environment variables of remote server(Y) so that full script will execute successfully.

NOTE : I don't have write access to etc directory so I can't change anything in it.

Thanks in advance!

Prasoon Gupta
  • 305
  • 1
  • 3
  • 11
  • 2
    Possible duplicate of [Why does an SSH remote command get fewer environment variables then when run manually?](http://stackoverflow.com/questions/216202/why-does-an-ssh-remote-command-get-fewer-environment-variables-then-when-run-man) – kaylum May 04 '17 at 06:54
  • No, i don't find my answer in it, that's why asked separately. – Prasoon Gupta May 04 '17 at 06:55
  • 1
    Why not. Did you read it fully? For example: "When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists". That is, did you try putting the env values in /etc/profile? There are several other suggestions - did you try all of them and none of them worked for you? If that is the case you need to say what you tried and why they were not suitable. – kaylum May 04 '17 at 07:02
  • I am not a super user for the server and hence I don't have write access in etc directory. That's why most of the solution on that link didn't work for me. – Prasoon Gupta May 04 '17 at 07:06
  • Well, that's a rather important constraint right? Suggest putting it into your question. – kaylum May 04 '17 at 07:07

2 Answers2

3

You can include your environment variables like following:

ssh user@host_y 'source ~/.bash_profile; /path/to/your/script/abc.sh'

Since direct command run is not an interactive shell, your variable will not work there. source will run script in your current shell and make visible environment variables in that file to your script.

scriptmonster
  • 2,741
  • 21
  • 29
2

I run some cron jobs using ssh connect a remote machine. The code can't load all the environment variables. It works if I run the code in that machine. I tried several ways that doesn't work for me. Finally, I comment below lines in the ~/.bashrc file. It works for me.

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

The ssh connect open an no-interactive shell. So it will load the environment variables for an non-interactive shell if you comment or delete this block codes.

Alternatively, you can just put all of your required environment lines code above that line.

Roy Yin
  • 55
  • 6