Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `timeout` not work with pipes?

Tags:

bash

pipe

timeout

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
like image 737
John Threepwood Avatar asked Aug 13 '12 22:08

John Threepwood


4 Answers

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"
like image 79
Shawn Chin Avatar answered Nov 11 '22 02:11

Shawn Chin


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.

like image 2
mjgpy3 Avatar answered Nov 11 '22 02:11

mjgpy3


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
like image 2
Thor Avatar answered Nov 11 '22 04:11

Thor


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
like image 1
Kombajn zbożowy Avatar answered Nov 11 '22 03:11

Kombajn zbożowy