Why do `sort | sed '1,5p'` and `sort | head -n 5` behave differently when pipefail is in use?

67 views Asked by At

there is a different strange behavior,when it comes to pipe.

bash --version

GNU bash, version 4.4.20

NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic

test A

    set -eux
    set -o pipefail
    
    ps aux | tail -n +2 | sort -k 3 -n -r | head -n 5 #the shell will exit after some times

test B

    set -eux
    set -o pipefail
    
    ps aux | tail -n +2 | sort -k 3 -n -r | sed -n "1,5p" #the shell will never exit however often I issue it

1

There are 1 answers

5
user1934428 On

From what I see, head closes the stdin (respectively terminates) after 5 lines have been read. If sort at this time is not done yet with feeding its result into the pipe, the stdout for sort is broken, and sort terminates with a non-zero exitcode. Since you have turned on pipefail, this generates a non-zero exitcode for the whole pipe. Since you also have turned on -e, this kills your shell.

OTOH, sed consumes the whole standard input. Therefore, sort can stuff everythin into its stdout and no pipe breaks.