Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

If I use

timeout 10 ssh -n -o BatchMode=yes 1.1.1.1 'sleep 20' > 1.1.1.1.txt 2>&1 &

To give out a remote command on a server, and I kill the SSH connection after 10 seconds, then I can see that the sleep 20 is still running on the server, but there is no SSH connection.

How can I kill the remote command after a timeout, say 10 seconds?

The remote machine is AIX 6.1 (or SLES) and no package is available for "timeout". My client is Ubuntu 10.03.

share|improve this question
1  
If you knew the PID of the command (I'm assuming you do, seeing as you can still see it running), you send it a TERM signal. –  MaxMackie Aug 20 '11 at 16:17

1 Answer 1

up vote 3 down vote accepted

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'
share|improve this answer
    
+1 for the kill %1 way; I've done that in some scripts in the past. –  Aaron D. Marasco Aug 21 '11 at 13:22
    
what does "kill %1" do? does it always kill the good process? what happensd if there are more processes sent to background with "&" ? –  LanceBaynes Aug 22 '11 at 8:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.