Linux – Different behaviour of script locally and over ssh

bashlinuxshell-scriptingunix

I have a script on a server-A

Script-A

#!/bin/bash -l
echo "script-A.sh" | change-environment.sh

When I ssh onto server-A and execute it, it works fine.
However, when I

ssh user@server-A ./script-A.sh

Script-A executes, but throws an undefined variable error in change-environment.sh.

change-environment.sh runs in the c shell(I have no control over the script so the method I have used is about the only way I can use it), but everything else is in bash.

Had found a similar question at I can run a script locally, but cannot do "ssh HOSTNAME /path/to/script.sh". However, there was no solution to the issue and it was a year old.

Best Answer

When using ssh with a command, it may not actually create a login shell even if your script uses #!/bin/bash -l.

Try ssh user@server-A bash -l, then run your script. You can also create something like

    #!/bin/bash
    export 

Then run it after logging in manually (ssh user@server-A) and when using ssh with a command (ssh user@server-A name-of-that-script.sh).

For instance, on Mac OS X, using ssh martin@nathan bash -l does not even set PS1, whereas as normal ssh martin@nathan interactive shell does.

Another important difference is that a pseudo-terminal is only allocated when running interactively (logging in without a command).