Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Last active April 12, 2024 17:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/11d846216a055f4f5d78ab740e639332 to your computer and use it in GitHub Desktop.
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.
#!/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
@malcolmgreaves
Copy link
Author

Example run with triggered signal causing exit during sleep --

Run until sleep:

$ ./x.sh
Local temporary directory: /Users/mgreaves/temp_install_space-82BC463E19766E59D88EEDEC25026BFE
writing!
/Users/mgreaves/temp_install_space-82BC463E19766E59D88EEDEC25026BFE
└── hi

1 directory, 1 file
sleep 10s
^Z
[1]  + 28879 suspended  ./x.sh

Inspecting while suspended:

$ ls /Users/mgreaves/temp_install_space-82BC463E19766E59D88EEDEC25026BFE
hi

Resuming and interrupting with SIGINT:

$ fg
[1]  - 28879 continued  ./x.sh
^C

Observe directory is gone:

$ ls /Users/mgreaves/temp_install_space-82BC463E19766E59D88EEDEC25026BFE
ls: /Users/mgreaves/temp_install_space-82BC463E19766E59D88EEDEC25026BFE: No such file or directory

@malcolmgreaves
Copy link
Author

malcolmgreaves commented Apr 12, 2024

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