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
/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
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.