Running a script on another host non–interactively

Running a script on another host non–interactively#

Once you can connect to a host using SSH you can of course run commands interactively while in the remote shell. You can also run a single command on the server and exit immediately with ssh HOST COMMAND [ARGUMENT…]. For example, ssh example.org export will start a remote shell, run the export command in the remote shell, and then exit the remote shell immediately.

There is a major issue with running anything but the most trivial commands this way: any characters which have a special meaning to the shell need to be escaped or quoted, otherwise they apply to the local shell. For example, ssh example.org cd /tmp '&&' echo "\$PWD" will open a shell on the server, change the working directory to /tmp, and finally print the value of $PWD as set by the server. This is cumbersome and error–prone.

A more subtle issue is that ssh HOST COMMAND [ARGUMENT…] will consume the client’s standard input to pass it to the remote command. Here’s a common way to run into this issue:

 

This page is a preview of The newline Guide to Bash Scripting

No discussions yet