I faced an urge to run different scripts simultaneously on different servers. (+/- 2 seconds not a problem) The condition is to launch the scripts by the invocation from the primary server, and NOT by the Cron schedule. I tried SSH, but this way I must wait till the script finishes running on the remote server and only then drop the session. I'm looking for an alternative way, that allows to start the script on remote server without waiting for its end. P.S. - I'm not using CLI in my use case, but an external script invocation app, that triggers the script on the primary server. Thanks.
screen will allow you to execute remote jobs without staying connected to the server, except on systems where
systemd kills all processes upon logout1. Specifically, you can use:
#!/bin/sh ssh server1 screen -d -m command1 ssh server2 screen -d -m command2 # ...
ssh session terminates immediately after launching the remote
screen process, which in turn exits as soon as the executed command finishes. You can suffix each
ssh line with
& to make the connections in parallel.
Excerpt from the manual,
screenin "detached" mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts.
1 If you are on a system that uses
systemd configured with
killUserProcesses=yes, you will need to replace
systemd-run --user --scope screen.
Use ‘& disown’ to send the command to a sub shell that is then disowned. Use nohup if you need process tracking. Below I used the sleep binary wrapped in a time call to give quick feedback in the console about what is going on.
time sleep 5
The shell is blocking, so you won’t be able to nicely exit the session.
time sleep 5 &
Is subshelled, so exiting will still kill the sleep command.
time nohup sleep 5 &
This subshells the nohup, so you’re doing better because of logging, but a sub shell will still be attached to the shell that created it and therefore it and it’s processes will be destroyed when the session ends. You really just need to disown it:
#!/bin/bash nohup sleep 500 & disown pid=$! echo $pid > /tmp/time.pid exit 0