Complete the shell script without waiting for the earlier parts of the pipeline

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 leads to the expected result (one line of "foo"), but sleeps (for the specified 100 seconds) until completion. I would like the script to terminate immediately when the head does. How to make bash actually exit immediately? Even changing the last line to

 long_running | (head -n 1; exit) 

or similar does not work; I cannot get set -e , another general suggestion, to work even if I have to fail, say (head -n 1; false) or the like.

(This is a simplified version of my real code (obviously) that is not sleeping, just creating a rather complicated set of nested pipelines looking for various solutions to the restriction problem, since I only need one, and I don’t care which one I get, I would like to complete the script. adding head -n 1 to the call ...)

+6
source share
1 answer

How about sending a 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 increase the number -n to a larger number, the dream will begin, but will exit as soon as the head ends.

+3
source

Source: https://habr.com/ru/post/904444/


All Articles