11

I'm writing a script and would like to know how to ask one of the commands to exit after few seconds. For eg. let's suppose my script runs 2 application commands in it.

#!/bin/bash

for i in `cat servers`
do
<command 1> $i >> Output_file  #Consistency command
<command 2> $i >> Output_file  #Communication check
done

These commands are to check consistency & communication to/from application. I want to know how do I make sure that command 1 & 2 runs for only few seconds and if there is no response from particular host, move on to next command.

codeforester
  • 39,467
  • 16
  • 112
  • 140
Marcos
  • 845
  • 3
  • 10
  • 21
  • 1
    You seem to be looking for this: [Timeout a command in bash without unnecessary delay](http://stackoverflow.com/questions/687948/timeout-a-command-in-bash-without-unnecessary-delay) – devnull May 23 '13 at 11:34
  • I had a look @ that, isn't there an easier way?? I don't want to make my tiny script too complex! :) – Marcos May 23 '13 at 19:07
  • this is useful for imagemagick's `display` command which doesn't play nicely with xargs. – Sridhar Sarnobat Feb 13 '17 at 01:38

1 Answers1

17

bash coreutils has got 'timeout` command.

From manual:

DESCRIPTION

Start COMMAND, and kill it if still running after NUMBER seconds. SUFFIX may be "s" for seconds (the default), "m" for minutes, "h" for hours or "d" for days.

for example:

timeout 5 sleep 6

Chris
  • 1,410
  • 12
  • 21