File tree Expand file tree Collapse file tree 1 file changed +57
-1
lines changed
cheatsheets/shell/scripting Expand file tree Collapse file tree 1 file changed +57
-1
lines changed Original file line number Diff line number Diff line change @@ -93,6 +93,47 @@ How do I get the output and exit value of a subshell when using `bash -e`? Usin
9393OUTPUT=$( INNER)
9494```
9595
96+
97+ ## Exit on error
98+
99+ ### Basic
100+
101+ ``` sh
102+ my-cmd || exit $?
103+
104+ # This will only run if `my-cmd` succeeded.
105+ # ...
106+ ```
107+
108+ Or
109+
110+ ``` sh
111+ my-cmd
112+
113+ if [[ $? -ne 0 ]]; then
114+ echo ' Error running my-cmd`'
115+
116+ exit 1
117+ fi
118+
119+ # This will only run if `my-cmd` succeeded.
120+ # ...
121+ ```
122+
123+
124+ Or simply set an attribute to make any errors cause an exit.
125+
126+ ``` sh
127+ set -e
128+
129+ my-cmd
130+
131+ # This will only run if `my-cmd` succeeded.
132+ # ...
133+ ```
134+
135+ ### Subshell
136+
96137``` sh
97138OUTPUT=$( INNER) || exit $?
98139echo $OUTPUT
102143
103144``` sh
104145if ! OUTPUT=$( INNER) ; then
105- exit $?
146+ exit $?
106147fi
107148echo $OUTPUT
108149```
150+
151+ In a function:
152+
153+ ``` sh
154+ whicha () {
155+ RESULT=$( which " $1 " )
156+
157+ if [[ $? -ne 0 ]]; then
158+ echo " $RESULT "
159+ return 1
160+ fi
161+
162+ # ...
163+ }
164+ ```
You can’t perform that action at this time.
0 commit comments