commit 37a2fed590bc50364bc598260ef9e83299a42d05
parent 09a68f140de89b768bf5b41ad0485068c791280d
Author: David Voznyarskiy <31452046-davidvoz@users.noreply.gitlab.com>
Date: Thu, 15 Jan 2026 23:07:05 -0800
exercise 31 trap added
Diffstat:
2 files changed, 56 insertions(+), 0 deletions(-)
diff --git a/exercises/31_trap.sh 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
@@ -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"