Reputation: 561
Consider the following script:
#!/bin/bash
function long_running {
for i in $(seq 1 10); do
echo foo
sleep 100
done
}
long_running | head -n 1
This produces the expected output (one line "foo") but sleeps (for the specified 100 seconds) before terminating. I would like the script to terminate immediately when head does. How can I force bash to actually quit immediately? Even changing the last line to
long_running | (head -n 1; exit)
or similar doesn't work; I can't get set -e
, another common suggestion, to work even if I force a failure with, say, (head -n 1; false)
or the like.
(This is a simplified version of my real code (obviously) which doesn't sleep; just creates a fairly complex set of nested pipelines searching for various solutions to a constraint problem; as I only need one and don't care which I get, I'd like to be able to make the script terminate by adding head -n 1
to the invocation...)
Upvotes: 6
Views: 477
Reputation: 77095
How about sending the function to head like this -
#!/bin/bash
function long_running {
for i in $(seq 1 10); do
echo foo
sleep 100
done
}
head -n 1 <(long_running)
Obviously if you will increase the -n
to a greater number, the sleep would kick in but would exit once head is completed.
Upvotes: 3