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
From what I see,
headcloses the stdin (respectively terminates) after 5 lines have been read. Ifsortat this time is not done yet with feeding its result into the pipe, the stdout forsortis broken, andsortterminates 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,
sedconsumes the whole standard input. Therefore,sortcan stuff everythin into its stdout and no pipe breaks.