[Linux] Use bash environment variables via SSH command

Recently I hit a problem when I setting our Jenkins testing system: we need to run a script via SSH command on a remote machine. However, the script itself depends on many environment variables which is set in .bashrc. Simple SSH command like this won’t work:

ssh user@ip "sh foo.sh"

because SSH command it is not a login terminal, nor an interactive terminal. Thus bash is not guaranteed to be invoke and environment variables won’t be load. Stack Overflow has a clear explanation. This cause our shell script fail because of unset variables.

However, the solutions posted on Stack Overflow does not work for me. After couple few hours exploration, I find a workable (but not very elegant) solution based on changing config of sshd

1. modify /etc/ssh/sshd_config, and insert these lines into the file

add PermitUserEnvironment yes
ForceCommand /etc/ssh/bar

here /etc/ssh/bar is the file we will add

2. add file /etc/ssh/bar, and set environment variables in the file. Or you can source other shell script. Example

export foofoo="FOOFOO"
export barbar="BARBAR"
source /home/user/env.sh

That’s it. The lesson I learn from this is don’t get environment variables and shell as granted, especially you are operating via ssh terminal.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s