How To Run Multiple SSH Command On Remote Machine And Exit Safely

How To Run Multiple SSH Command On Remote Machine And Exit Safely

To run multiple SSH commands on a remote machine and exit safely, you can use the ssh command with the -t option to force pseudo-terminal allocation, and then use the && operator to chain multiple commands together.

Here is an example of how to run multiple SSH commands on a remote machine and exit safely:

ssh user@remote "command1 && command2 && command3 && exit"
Sourc‮e‬:www.lautturi.com

This will run the command1, command2, and command3 commands on the remote machine, and then exit the SSH session safely.

The -t option is necessary to force pseudo-terminal allocation, which is required in order to run multiple commands. Without the -t option, the && operator will not work as expected and the commands will not be executed correctly.

Keep in mind that the && operator only executes the next command if the previous command was successful (exit code 0). If any of the commands fail (exit code non-zero), the rest of the commands will not be executed and the SSH session will not be exited safely.

You can also use the ; operator to chain multiple commands together, but this operator will execute all commands regardless of the exit code of the previous command. This may not be desirable if you want to exit the SSH session safely in case of an error.

Created Time:2017-10-29 22:08:30  Author:lautturi