Bash: Head & Tail behavior with bash script

后端 未结 3 1070
北荒
北荒 2020-12-29 04:49

Suppose I have following script:-

test.sh

#!/bin/bash
command1  #prints 5 lines
command2  #prints 3 lines

I run th

3条回答
  •  借酒劲吻你
    2020-12-29 05:35

    Nice finding. According to my tests it's exactly like you said. For example I have this script that just eats cpu, to let us spot it in top:

    for i in `seq 10`
      do echo $i
      x=`seq 10000000`
    done
    

    Piping the script with head -n1 we see the command returning after the first line. This is the head behavior: it completed its work, so it can stop and return the control to you.

    The input script should continue running but look what happens: when the head returns, its pid doesn't exist anymore. So when linux tries to send the output of the script to the head process, it does not find the process, so the script crashes and stops.

    Let's try it with a python script:

    for i in xrange(10):
        print i
        range(10000000)
    

    When running it and piping to head you have this:

    $ python -u test.py | head -n1
    0
    Traceback (most recent call last):
      File "test.py", line 2, in 
        print i
    IOError: [Errno 32] Broken pipe
    

    The -u option tells python to automatically flush the stdin and stdout, as bash would do. So you see that the program actually stops with an error.

提交回复
热议问题