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.
Asked
Active
Viewed 2.4k times
2 Answers
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 ;-))
Stéphane Gimenez
- 28,907
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
- My answer on Stack Overflow here: All about redirection in bash
Gabriel Staples
- 2,562
-
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
timeouton a child shell:timeout 0.5 sh -c 'cat /dev/xxx' >outalthough 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
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:42timeout 5s viwill run the editor for 5 seconds and will sendSIGTERM. You can usehanddfor hours and days. – vdi Apr 23 '20 at 08:02