Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit from a command after n seconds? [duplicate]

Tags:

bash

exit

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.

like image 926
Marcos Avatar asked May 23 '13 10:05

Marcos


People also ask

How do I run a Linux script in 5 seconds?

What you could do is write a shell script with an infinite loop that runs your task, and then sleeps for 5 seconds. That way your task would be run more or less every 5 seconds, depending on how long the task itself takes. You can create a my-task.sh file with the contents above and run it with sh my-task.sh .

How do you repeat a command in Linux?

First, the easiest way to repeat a command is simply by typing !!. If you were logged into a Linux server and waiting for a coworker to log in, for example, you might want to repeat the who command shown below until you see your coworker's username. Typing !! after the initial who command will do this for you.

How do you use the exit command?

To close or exit the Windows command line window, also referred to as command or cmd mode or DOS mode, type exit and press Enter . The exit command can also be placed in a batch file. Alternatively, if the window is not fullscreen, you can click the X close button in the top-right corner of the window.

Which command will give exit status of previously executed command?

echo $? 2. It returns the exit status of the last executed command.


1 Answers

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

like image 194
Chris Avatar answered Sep 30 '22 12:09

Chris