One-time temporary directories under Linux
Posted
Occasionally I want to try some code out that I’ve found on GIT.
Particularly for code that is not natively supported on a given target platform, trying to make
it is often much quicker than reading the documentation.
It’s just the hassle of cleaning up after myself that is a pain, particularly if you’ve cloned the code into an existing directory by mistake.
Hence, I’ve created a little helper (I named it mtd
, short for make temp directory), with the following source code.
#!/bin/bash
# Create a temporary directory and store its name in a variable...
TMPDIR=$(mktemp -d)
# Exit if the temp directory wasn't created successfully
if [ ! -e $TMPDIR ]; then
echo "Failed to create temp directory $TMPDIR"
exit 2
fi
# Make sure it gets removed even if the script exits abnormally
trap "exit 1" HUP INT PIPE QUIT TERM
trap 'printf "Removing $TMPDIR..." && rm -rf "$TMPDIR" && echo "Done."' EXIT
# Spawn the shell
echo "Starting a new shell in $TMPDIR... Type 'exit' to clean up."
cd $TMPDIR
bash --init-file <(echo "[ -f ~/.profile ] && . ~/.profile; \
[ -f ~/.bashrc ] && . ~/.bashrc")