Search code examples
bashsshjobs

How to prevent background command going to suspend immediately


Imagine this script (do not consider auth and other stuff, all SSH commands run just fine without &)

(ssh foo.com "/bin/sleep 5 && echo 1") &
(ssh bar.com "/bin/sleep 5 && echo 1") &
wait
echo "My commands finished"

Now, I would expect all my SSH commands to run immediately as background jobs and then, when finished, I would get the final "My commands finished" message.

But that's not what happens...

What actually happens is this

[1] 16155
[1]  + 16155 suspended (tty input)  ssh foo.com "/bin/sleep 5 && echo 1"
[2] 16156
[2]  + 16156 suspended (tty input)  ssh bar.com "/bin/sleep 5 && echo 1"
My commands finished

So all the background commands go immediatelly to suspended state where they stay forever. Sure I can bring them back with fg or kill -CONT PID but that's all sequential. I need to run all my commands in parallel and just wait for all of them to finish.

Do you know why is that and how to avoid the suspended state?


Solution

  • Thanks to n.m.. The solution is to pass < /dev/null to stdin. By doing that the subprocess closes the stdin and does not block console IO as in the previous case which led to suspend state.