Note that there are some explanatory texts on larger screens.

plurals
  1. POTimeout a command in bash without unnecessary delay
    text
    copied!<p><a href="https://stackoverflow.com/questions/601543#637753">This answer</a> to <a href="https://stackoverflow.com/questions/601543">Command line command to auto-kill a command after a certain amount of time</a> </p> <p>proposes a 1-line method to timeout a long-running command from the bash command line:</p> <pre><code>( /path/to/slow command with options ) &amp; sleep 5 ; kill $! </code></pre> <p>But it's possible that a given "long-running" command may finish earlier than the timeout. (Let's call it a "typically-long-running-but-sometimes-fast" command, or <em>tlrbsf</em> for fun.)</p> <p>So this nifty 1-liner approach has a couple of problems. First, the <code>sleep</code> isn't conditional, so that sets an undesirable lower bound on the time taken for the sequence to finish. Consider 30s or 2m or even 5m for the sleep, when the <em>tlrbsf</em> command finishes in 2 seconds &mdash; highly undesirable. Second, the <code>kill</code> is unconditional, so this sequence will attempt to kill a non-running process and whine about it.</p> <p>So...</p> <p><strong>Is there a way</strong> to timeout a typically-long-running-but-sometimes-fast (<em>"tlrbsf"</em>) command that</p> <ul> <li>has a bash implementation (the other question already has Perl and C answers)</li> <li>will terminate at the earlier of the two: <em>tlrbsf</em> program termination, or timeout elapsed</li> <li>will not kill non-existing/non-running processes (or, optionally: will not <em>complain</em> about a bad kill)</li> <li>doesn't have to be a 1-liner</li> <li>can run under Cygwin or Linux</li> </ul> <p>... and, for bonus points, runs the <em>tlrbsf</em> command in the foreground and any 'sleep' or extra process in the background, such that the stdin/stdout/stderr of the <em>tlrbsf</em> command can be redirected, same as if it had been run directly?</p> <p>If so, please share your code. If not, please explain why.</p> <p>I have spent awhile trying to hack the aforementioned example but I'm hitting the limit of my bash skills.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload