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:
#!/bin/bash
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.