From e3f51c862c77aec224741657f9dd489bd2ea2600 Mon Sep 17 00:00:00 2001 From: swg Date: Sat, 17 Feb 2024 22:45:29 +0100 Subject: [PATCH] Clean up function snippet added with tests. --- README.md | 17 ++++++++++++++++- clean_up.sh | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100755 clean_up.sh diff --git a/README.md b/README.md index f03b0c8..e08d3ff 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,19 @@ function call: ``` check_folder_for_extension ./cffe_test "*.jpg *.JPG" ``` -For multiple extensions (or other parts of the file name to match) space separate the list, like shown above. \ No newline at end of file +For multiple extensions (or other parts of the file name to match) space separate the list, like shown above. + +## Clean up + +Cleaning up in a script and exit with a given exit code. + +function call: +``` +clean_up 0; +``` + +For testing the function call the script with: +``` +clean_up.sh test +``` + diff --git a/clean_up.sh b/clean_up.sh new file mode 100755 index 0000000..a3e30c4 --- /dev/null +++ b/clean_up.sh @@ -0,0 +1,47 @@ +#!/bin/bash +## Simple function for exiting a bash script with a given return value. +## Uses bash snippet logger. + +## Cleanup and exit with exit value given. +## param 1 Exit value. +function clean_up() { + local _exit_val=$1; + echo "Cleaning up on exit $_exit_val."; + + # add cleanup code here + + echo "Exiting on $_exit_val."; + exit $_exit_val; +} + +## Test the clean_up() function. +Param=$1; +Test="test" +if [[ ${Param} = $Test ]]; then + printf "Running tests for clean_up() with Param ${Param}.\n"; + ## testing exit code 1 + exit_code1=1; + printf "Test1 with exit code $exit_code1.\n"; + ./clean_up.sh $exit_code1; + ret1=$?; + if [[ ${ret1} -eq ${exit_code1} ]]; then + printf "Test1 with ${exit_code1} ok.\n" + else + printf "Test1 with ${exit_code1} FAILED: got ${ret1}.\n" + fi + ## testing exit code 0 + exit_code2=0; + printf "Test2 with exit code $exit_code2.\n"; + ./clean_up.sh $exit_code2; + ret2=$?; + if [[ ${ret2} -eq ${exit_code2} ]]; then + printf "Test2 with ${exit_code2} ok.\n" + else + printf "Test2 with ${exit_code2} FAILED: got ${ret2}.\n" + fi + exit 0; +else + printf "Cleanup test with ${Param}.\n"; + clean_up ${Param}; + exit 0; +fi