8

The following command line call of timeout (which makes no sense, just for testing reason) does not work as expected. It waits 10 seconds and does not stop the command from working after 3 seconds. Why ?

timeout 3 ls | sleep 10
John Threepwood
  • 15,593
  • 27
  • 93
  • 149

4 Answers4

22

What your command is doing is running timeout 3 ls and piping its output to sleep 10. The sleep command is therefore not under the control of timeout and will always sleep for 10s.

Something like this would give the desired effect.

timeout 3 bash -c "ls | sleep 10"
Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
2

The 'ls' command shouldn't be taking 3 seconds to run. What I think is happening is you are saying (1) timeout on ls after 3 seconds (again this isn't happening since ls shouldn't take anywhere near 3 seconds to run), then (2) pipe the results into sleep 10 which does not need further arguments than the number you are giving it. Thus ls happens, timeout doesn't matter, and bash sleeps for 10 seconds.

mjgpy3
  • 8,597
  • 5
  • 30
  • 51
  • 4
    `ls` can take a very long time to run in a directory with a large number of files. – jordanm Aug 13 '12 at 22:36
  • 1
    Absolutely, you are correct. I made a few assumptions I shouldn't have in that answer, thank you for the insight. – mjgpy3 Aug 14 '12 at 02:22
2

The only way I know how to get the effect you're after, is to put the piped commands into a separate file:

cat > script
ls | sleep 10
^D

timeout 3 sh script
Thor
  • 45,082
  • 11
  • 119
  • 130
  • 1
    You can use process substitition to do that inline and avoid the temporary file -- `timeout 3 sh <(echo "ls | sleep 10")` – Shawn Chin Aug 15 '12 at 13:31
1

It is enough to set the timeout on the last command of the pipeline:

# Exits after 3 seconds with code 124
ls | timeout 3 sleep 10

# Exits after 1 second with code 0
ls | timeout 3 sleep 1
Kombajn zbożowy
  • 8,755
  • 3
  • 28
  • 60
  • "A duration of 0 disables the associated timeout. Note that the actual timeout duration is dependent on system conditions, which should be especially considered when specifying sub-second timeouts." Exit status: * 124 if COMMAND times out * 125 if ‘timeout’ itself fails * 126 if COMMAND is found but cannot be invoked * 127 if COMMAND cannot be found * 137 if COMMAND is sent the KILL(9) signal (128+9) * the exit status of COMMAND otherwise – ShpielMeister Aug 13 '21 at 04:09