Skip to content

Commit 8775372

Browse files
committedNov 16, 2024
Add Gracefully Exit A Script With Trap as a Unix TIL
1 parent 1513611 commit 8775372

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed
 

‎README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1507 TILs and counting..._
13+
_1508 TILs and counting..._
1414

1515
---
1616

@@ -1465,6 +1465,7 @@ _1507 TILs and counting..._
14651465
- [Global Substitution On The Previous Command](unix/global-substitution-on-the-previous-command.md)
14661466
- [Globbing For All Directories In Zsh](unix/globbing-for-all-directories-in-zsh.md)
14671467
- [Globbing For Filenames In Zsh](unix/globbing-for-filenames-in-zsh.md)
1468+
- [Gracefully Exit A Script With Trap](unix/gracefully-exit-a-script-with-trap.md)
14681469
- [Grep For Files Without A Match](unix/grep-for-files-without-a-match.md)
14691470
- [Grep For Files With Multiple Matches](unix/grep-for-files-with-multiple-matches.md)
14701471
- [Grep For Multiple Patterns](unix/grep-for-multiple-patterns.md)
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Gracefully Exit A Script With Trap
2+
3+
With `trap` you can intercept signals that would cause your script to exit and
4+
then inject some additional behavior. Perhaps you want to make sure the script
5+
cleans up after itself before it exists.
6+
7+
During this script's execution, it creates a file in the filesystem. It would
8+
be nice to make sure that no matter path this script ends up down that it will
9+
clean up after itself as it exits. We set up a `trap` that looks for the `EXIT`
10+
signal to do this.
11+
12+
```bash
13+
# Set up trap
14+
trap 'echo "Cleaning up temp files"; rm -f *.tmp' EXIT
15+
16+
# Create temporary file
17+
echo "test data" > work.tmp
18+
19+
# Do some work
20+
cat work.tmp
21+
22+
# Trap will clean up on exit
23+
```
24+
25+
Whatever is in quotes is what the trap will execute when it is triggered. The
26+
following one or more signals are what the trap listens for, in this case
27+
`EXIT`.
28+
29+
[source](https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_12_02.html)

0 commit comments

Comments
 (0)