File tree 2 files changed +31
-1
lines changed
2 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1507 TILs and counting..._
13
+ _ 1508 TILs and counting..._
14
14
15
15
---
16
16
@@ -1465,6 +1465,7 @@ _1507 TILs and counting..._
1465
1465
- [ Global Substitution On The Previous Command] ( unix/global-substitution-on-the-previous-command.md )
1466
1466
- [ Globbing For All Directories In Zsh] ( unix/globbing-for-all-directories-in-zsh.md )
1467
1467
- [ 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 )
1468
1469
- [ Grep For Files Without A Match] ( unix/grep-for-files-without-a-match.md )
1469
1470
- [ Grep For Files With Multiple Matches] ( unix/grep-for-files-with-multiple-matches.md )
1470
1471
- [ Grep For Multiple Patterns] ( unix/grep-for-multiple-patterns.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments