0

I have been reading about bash set -e option, and still a bit confused on why the below pipe continues to execute when the file test-output.xml does not exist.

Is setting set -e only applicable to the exit status of the last command? I can't find this statement (well, explicitly) in the documentation(s) for this option (e.g. tldp.org -> bash options).

Thank you for all your help!

#!/usr/local/bin/bash

set -e
fail_tests=`cat test-output.xml|grep '^<testng-results '|perl -e 'print "0";'`
echo $?
echo "fail_tests: [$fail_tests]"

outputs:

cat: test-output.xml: No such file or directory
0
fail_tests: [0]

However, if I change the command to:

#!/usr/local/bin/bash

set -e
fail_tests=`cat test-output.xml|grep '^<testng-results '|perl -e 'print "0"; exit 1;'`
echo $?
echo "fail_tests: [$fail_tests]"

it outputs:

cat: test-output.xml: No such file or directory

running with bash version:

➜  ~ /usr/local/bin/bash -version
GNU bash, version 5.0.18(1)-release (x86_64-apple-darwin19.5.0)
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
G T
  • 37
  • 4
  • 2
    Need `pipefail` You want `set -o errexit pipefail` – Léa Gris Aug 18 '20 at 18:29
  • 2
    Why are you using `cat` with `grep`? Don't [abuse `cat`](https://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat). – Kulfy Aug 18 '20 at 18:30
  • 1
    That said, it's wise to read and fully understand [BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105) (skipping the allegory for the exercises if in a hurry) before trusting `set -e`. – Charles Duffy Aug 18 '20 at 18:32
  • 1
    Dupe of https://stackoverflow.com/questions/32684119/exit-when-one-process-in-pipe-fails – Léa Gris Aug 18 '20 at 18:33
  • @Kulfy You're right, I am just a messenger time [ i.e. this is not my script, however, I was the one debugging :) ]. Regardless, thank you! – G T Aug 18 '20 at 18:34

1 Answers1

1

Indeed, the exit code of a pipeline is the exit code of the last command in the pipeline. So, by default set -e only applies to the last command in each pipeline.

Bash has set -o pipefail to extend the behavior or set -e to any command in a pipeline.

tripleee
  • 175,061
  • 34
  • 275
  • 318