1 | #!/usr/bin/env bash
|
2 | #
|
3 | # Pattern for testing if a function has succeeded or failed with set -e:
|
4 | #
|
5 | # SUMMARY: Call it through $0.
|
6 | #
|
7 | # Useful for test frameworks!
|
8 | #
|
9 | # Usage:
|
10 | # demo/dollar0-errexit.sh <function name>
|
11 |
|
12 | set -o nounset
|
13 | set -o pipefail
|
14 | set -o errexit
|
15 |
|
16 | # Should produce TWO lines, not THREE.
|
17 | # And the whole thing FAILS with exit code 1.
|
18 | myfunc() {
|
19 | echo one
|
20 | echo two
|
21 | false # should FAIL here
|
22 | echo three
|
23 | }
|
24 |
|
25 | mypipeline() { myfunc | wc -l; }
|
26 |
|
27 | # Prints three lines because errexit is implicitly disabled.
|
28 | # It also shouldn't succeed.
|
29 | bad() {
|
30 | if myfunc | wc -l; then
|
31 | echo true
|
32 | else
|
33 | echo false
|
34 | fi
|
35 | echo status=$?
|
36 | }
|
37 |
|
38 | # This fixes the behavior. Prints two lines and fails.
|
39 | good() {
|
40 | if $0 mypipeline; then
|
41 | echo true
|
42 | else
|
43 | echo false
|
44 | fi
|
45 | echo status=$?
|
46 | }
|
47 |
|
48 | # This is pretty much what 'bad' is dong.
|
49 | not-a-fix() {
|
50 | set +o errexit
|
51 | mypipeline
|
52 | local status=$?
|
53 | set -o errexit
|
54 |
|
55 | if test $? -eq 0; then
|
56 | echo true
|
57 | else
|
58 | echo false
|
59 | fi
|
60 | echo status=$?
|
61 | }
|
62 |
|
63 | "$@"
|