Last active
April 12, 2024 17:59
-
-
Save malcolmgreaves/11d846216a055f4f5d78ab740e639332 to your computer and use it in GitHub Desktop.
Reusable bash functions for creating a local temporary directory with rm exit trap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
#################################################################### | |
# | |
# Reusable functions for creating a local temporary directory: | |
# - [mk_tmp_dir] create local directory with unique name | |
# - [cleanup] add exit trap to rm this directory | |
# | |
# Use is always in the 2-call pattern: | |
# D=$(mk_tmp_dir) | |
# trap "cleanup $D" EXIT | |
# | |
cleanup() { | |
rm -rf "${1}" | |
} | |
mk_tmp_dir() { | |
# https://stackoverflow.com/a/10823731/362021 | |
local UUID=$(hexdump -n 16 -v -e '/1 "%02X"' /dev/urandom) | |
local TEMP_INSTALL="$(pwd)/temp_install_space-${UUID}" | |
mkdir "${TEMP_INSTALL}" | |
echo "${TEMP_INSTALL}" | |
} | |
#################################################################### | |
# Example use | |
name=$(mk_tmp_dir) | |
trap "cleanup $name" EXIT | |
echo "Local temporary directory: $name" | |
echo "writing!" | |
echo "hello world!" > "${name}/hi" | |
tree "${name}" | |
s=10 | |
printf "sleep %ds\n" $s | |
sleep $s |
Example run with normal exit --
Run and let program exit normally after sleep
:
$ time ./x.sh
Local temporary directory: /Users/mgreaves/temp_install_space-7D2747042EC24D15DD66DD5D8C56C758
writing!
/Users/mgreaves/temp_install_space-7D2747042EC24D15DD66DD5D8C56C758
└── hi
1 directory, 1 file
sleep 10s
./x.sh 0.01s user 0.03s system 0% cpu 10.085 total
Directory is gone after program exits normally:
$ ls /Users/mgreaves/temp_install_space-7D2747042EC24D15DD66DD5D8C56C758
ls: /Users/mgreaves/temp_install_space-7D2747042EC24D15DD66DD5D8C56C758: No such file or directory
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example run with triggered signal causing exit during
sleep
--Run until sleep:
Inspecting while suspended:
Resuming and interrupting with SIGINT:
Observe directory is gone: