Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use environment variables of remote server in ssh command

Tags:

linux

shell

ssh

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!

like image 466
Prasoon Gupta Avatar asked May 04 '17 06:05

Prasoon Gupta


2 Answers

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.

like image 76
scriptmonster Avatar answered Oct 20 '22 05:10

scriptmonster


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.

like image 31
Roy Yin Avatar answered Oct 20 '22 06:10

Roy Yin