shelllings

a practical way to learn shell
git clone https://git.davidvoz.net/shelllings.git
index
logs
tree
license

commit 37a2fed590bc50364bc598260ef9e83299a42d05
Author: David Voznyarskiy <31452046-davidvoz@users.noreply.gitlab.com>
Date:   Thu Jan 15 23:07:05 2026 -0800

    exercise 31 trap added

diff --git a/exercises/31_trap.sh b/exercises/31_trap.sh
new file mode 100644
index 0000000..279f5bb
--- /dev/null
+++ b/exercises/31_trap.sh
@@ -0,0 +1,32 @@
+#!/bin/sh
+
+# 'trap' is a very useful tool that I've been using on the exercises
+# where I said you didn't have to worry about deleting the created file.
+#
+# $ trap command SIGNAL
+#
+# For example, in your tests/ files, many will have trap statements
+#
+# $ cleanup() {
+# $ [ -f "file" ] && rm file
+# $ }
+# $ trap cleanup EXIT
+#
+# exit is the signal for trap to call cleanup(). Below are the different
+# signals that trap detects in standard POSIX
+#
+# $ trap command EXIT # catches both exit 1 and exit 0
+# $ trap command INT # catches ctrl+c kills
+# $ trap command TERM # catches a signal terminate, like 'kill'
+# $ trap command INT EXIT # catches different instances
+#
+# You don't have to call functions when running trap, you can run
+# commands in the same line
+#
+# $ trap 'echo "Exiting.."; exit' TERM
+#
+# Below is a simple creation of a file, write a trap line that prints
+# out "Removing..." and removes the file
+
+touch file.txt
+echo "kill me" > file.txt
diff --git a/tests/31_trap.sh b/tests/31_trap.sh new file mode 100644 index 0000000..fcc49e7
--- /dev/null
+++ b/tests/31_trap.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+
+set -eu
+RED="\033[31m"
+GREEN="\033[32m"
+RESET="\033[0m"
+
+cleanup() {
+ [ -f "file.txt" ] && rm -f file.txt
+}
+trap cleanup EXIT
+
+failed() {
+ printf "${RED}Failed${RESET}\n"
+ exit 1
+}
+
+sh exercises/31_trap.sh | grep -Eq "Removing..." || failed
+
+grep 'trap' exercises/31_trap.sh | grep "rm file\.txt" | grep 'Removing...' | grep -q 'EXIT' || failed
+
+[ -f "file.txt" ] && failed
+
+printf "${GREEN}Passed${RESET}\n"