Using ssh to execute a remote script in the background doesn't exit immediately

Why the follow ssh command doesn't exit immediately. Instead, it will exit after 1m

ssh -vvv <usr>@<ip> 'sh -c "sleep 60 &"'

But I do tell shell to run sleep command in the background, I don't know why

1 answer

  • answered 2019-11-14 05:12 anishsane

    It's because the file descriptors opened by the sh process are indirectly connected to your ssh session's tty.
    sleep command does not take anything on stdin not does it send anything back to stdout/stderr. However, the FDs inherited from sh are still open.

    The way out is to close those FDs by ip/op/err redirection.

    ssh -vvv <usr>@<ip> 'sh -c "sleep 60 &" &>/dev/null </dev/null'