60

I want know how I can run a command for a specified time say, one minute and if it doesn't complete execution then I should be able to stop it.

nikhil
  • 1,012

2 Answers2

77

Use timeout:

NAME
       timeout - run a command with a time limit

SYNOPSIS
       timeout [OPTION] DURATION COMMAND [ARG]...
       timeout [OPTION]

(Just in case, if you don't have this command or if you need to be compatible with very very old shells and have several other utterly specific requirements… have a look at this this question ;-))

  • 1
    Perfect, thanks for linking to that question. I didn't have timeout on my system but I do now. Just on a side note, is timeout bundled with the majority of linux distributions? – nikhil Oct 24 '11 at 04:28
  • 1
    Pretty cool. you can do something like this: for i in \seq 0 3`; do timeout 2 ethtool -p eth$i; done;` to blink LED's on NIC's – user1527227 Jun 19 '14 at 16:42
  • 2
    What a sexy command. Thanks for pointing it out, wasn't aware of it. – Bruno Bieri Mar 16 '17 at 14:16
  • Example: timeout 5s vi will run the editor for 5 seconds and will send SIGTERM. You can use h and d for hours and days. – vdi Apr 23 '20 at 08:02
0

How to use timeout with redirection to a file

For the cat case in this question here (emphasis added):

How can I cat a large file for, lets say, 45 seconds and output it to the screen or redirect to another file.

If you ever need this:

cat /dev/ttyUSB0 > out.txt

...instead of just this:

cat /dev/ttyUSB0

Then timeout won't work:

# This *does* work!: timeout after 0.5 sec
timeout 0.5 cat /dev/ttyUSB0

Does NOT work: try to redirect a response over serial to a file.

Using timeout with redirection of stdout to a file does not

seem to work!

timeout 0.5 cat /dev/ttyUSB0 > out.txt

So, the work-around that does work is to store the output into a variable first, using timeout on that part only, and then to write that to a file, like this:

response_str="$(timeout 0.5 cat /dev/ttyUSB0)"
printf "%s" "$response_str" > out.txt

See also

  1. My answer on Stack Overflow here: All about redirection in bash
  • Your answer is touching on the topic of timing things out, but only handles only an odd niche case. A neater solution would be to use timeout on a child shell: timeout 0.5 sh -c 'cat /dev/xxx' >out although I can't get the blocking behaviour that you describe to happen unless I redirect into or out of the device (or named pipe). – Kusalananda Oct 13 '22 at 17:51