How to kill a command started over SSH - the SSH connection lost

Assuming your remote server has a POSIX-compliant shell, the following should work:

ssh ...options... 'command & pid=$!; sleep 20; kill $pid'

Indeed the POSIX standard states about $!:

Expands to the decimal process ID of the most recent background command (see Lists) executed from the current shell. (For example, background commands executed from subshells do not affect the value of "$!" in the current shell environment.) For a pipeline, the process ID is that of the last command in the pipeline.

If the remote system has job control, you can shorten it this way:

ssh ...options... 'command & sleep 20; kill %1'

Tags:

Ssh

Timeout