Running commands after ampersand symbol & in a remote ssh session Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Running commands after ampersand symbol & in a remote ssh session without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a shell script that initiates a long, resource-intensive command on several different machines.

In order to execute the script on each machine in parallel, I have an ampersand symbol after each remote command in the for-loop.

while read host; 
    ssh -f "$host" "/home/user/" &
done < ~/cluster

However, as a consequence, I do not get the shell prompt back at the end of the for-loop. This prevents me from executing other scripts after has finished running on all of the machines.

For example, I want to be able to run a command such as:

./ && ./

However, currently initialize-cluster never “finishes.”

I’d like subsequent commands to execute only after all of the scripts finish on the remote machines.


Nothing in this script should prevent execution of the next command or return to the shell prompt. What could be giving the impression that the prompt is gone is the output of the remote scripts, which would arrive after return to the shell. To avoid that you could redirect stdout/stderr to some log file.

Since the remote commands are run in the background the original script will finish before the allocate scripts have finished executing: the next command can’t assume that initialization is complete. In order to start all initializations in parallel and wait for them all to finish you could do the following:

while read host 
  ssh "$host" "/home/user/" &
done < ~/cluster

And then it should be possible to:

./ && ./

The key here is the wait command, which waits for child processes to finish.

We are here to answer your question about Running commands after ampersand symbol & in a remote ssh session - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji