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.

2 Answers 2


Use timeout:

       timeout - run a command with a time limit

       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, 2011 at 4: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 Jun 19, 2014 at 16:42
  • 2
    What a sexy command. Thanks for pointing it out, wasn't aware of it. Mar 16, 2017 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, 2020 at 8:02

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
  • 1
    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, 2022 at 17:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .