I have a bash script that runs a command from which I want to get only the first line of output.

The obvious answer is some_command | head -1, right? Well, this works 99% of the time, but when the output was large enough it sometimes failed with exit code 141 since I have set -eo pipefail at the top. awk '{ print; exit; }' works for more cases, but still fails with large enough output. This simple script reproduces the problem:

set -eo pipefail
seq 1 100000 | awk '{ print; exit; }' | tee
echo "This is not printed"

This prints "1", but does not print "This is not printed". As I understand, awk (or head) exits before the input command (seq here) does, so the input command fails with SIGPIPE (141). I could of course work around it by setting +e just before the command in question and manually checking the exit code, but is there a better way?

I don't really want to remove the -o pipefail since I do want the script to fail if any of the commands in the path actually fail.


1 Answer 1


sed -n 1p works!

It appears to read all input, thus avoiding SIGPIPE. Even with seq 1 10000000 | sed -n 1p the delay is less than two seconds, and any real input would be way less than 10M lines.

Credit to Jonathan Leffler: https://stackoverflow.com/a/1429628/1536933 - that answer deserves all the upvotes!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .