‹ All Linux Interview Questions questions

Linux Interview Question 7: Pipeline Exit Status Pipefail

Linux Interview Questions · Test 1 · question 7 of 10

Shell, Text Processing & Pipeshard

A nightly bash script begins with set -e and contains these two lines:

grep ERROR /var/log/app/today.log | sort | uniq -c > /tmp/report.txt

echo "report ok"

One night /var/log/app/today.log does not exist. grep prints No such file or directory to stderr, but the script still prints report ok, exits with status 0, and the monitoring job treats the run as a success. Why did the script not stop, and what change makes it fail on this error?

Select one answer
Show answer and explanation

Answer:

  • B. A pipeline's exit status is that of its last command, which succeeded; add set -o pipefail so the failing grep makes the whole pipeline fail

In bash, the return status of a pipeline is the exit status of its last command. Here that is uniq -c, which happily processed empty input and returned 0, so the pipeline "succeeded" and set -e had nothing to react to, even though grep exited with status 2 (grep uses 0 for a line selected, 1 for no lines selected, 2 for an error). With set -o pipefail, the pipeline's status becomes that of the rightmost command that exited non-zero, so grep's 2 propagates and set -e aborts the script. Many teams start scripts with set -euo pipefail for this reason.

An interviewer may probe the follow-up: with pipefail, a night with no ERROR lines also fails, because grep returns 1 on no match. Handle that case explicitly if it counts as success.

Option A is wrong because redirection does not exempt a command from set -e; the exit status is what matters, and tee would leave the pipeline's last command still succeeding.

Option C misstates grep's exit codes: a missing file is an error and returns 2, not 0. An existence test would catch this one case, but not other failures early in the pipeline.

Option D is wrong because set -e looks only at exit statuses, never at stderr output. The error message was printed; it simply did not affect the pipeline's status.

References: bash(1) - Linux manual page; grep(1) - Linux manual page

Practice Test 1 ›

Study guides for Linux Interview Questions