Skip to content

Commit aca9681

Browse files
Update exit-status.md
1 parent cb3948c commit aca9681

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

cheatsheets/shell/scripting/exit-status.md

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,47 @@ How do I get the output and exit value of a subshell when using `bash -e`? Usin
9393
OUTPUT=$(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
97138
OUTPUT=$(INNER) || exit $?
98139
echo $OUTPUT
@@ -102,7 +143,22 @@ Or
102143

103144
```sh
104145
if ! OUTPUT=$(INNER); then
105-
exit $?
146+
exit $?
106147
fi
107148
echo $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+
```

0 commit comments

Comments
 (0)