Skip to content

Instantly share code, notes, and snippets.

@simurq
Created January 24, 2024 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simurq/38fadad2ce76ac6cdd62e38dec9e3da8 to your computer and use it in GitHub Desktop.
Save simurq/38fadad2ce76ac6cdd62e38dec9e3da8 to your computer and use it in GitHub Desktop.
POPPI Comments: `set -o pipefail`
Changes the behavior of the return code of a pipeline, which is normally the exit status of the last command in the pipe.
With `set -o pipefail`, the return code of a pipeline is the value of the last command that failed, or zero if all commands succeeded.
This maeks it possible to detect and handle errors that occur in any part of the pipe, not just the end.
E.g., suppose we have a script that uses the following pipeline:
$ cat file.txt | grep "foo" | wc -l
This pipeline counts the number of lines in 'file.txt' that contain the word 'foo'. If 'file.txt' does not exist, the `cat` command will
fail and print an error message, but the pipeline will still return zero, because the `wc -l` command succeeds. This means that the
script will not be aware of the failure and will continue as if nothing went wrong.
With `set -o pipefail` at the beginning of the script, however, the pipeline will return the exit status of `cat`, which is non-zero.
This way, we can check the return code and act accordingly, such as printing a custom error message or exiting the script.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment