Skip to content

Instantly share code, notes, and snippets.

@nilium
Last active August 10, 2019 19:13
Show Gist options
  • Save nilium/86305fb3a315e0f999bfe3f19ba90d21 to your computer and use it in GitHub Desktop.
Save nilium/86305fb3a315e0f999bfe3f19ba90d21 to your computer and use it in GitHub Desktop.
Script to generate an eval-able line to create a temporary file, assign it to a variable, and remove it upon exit.
#!/bin/bash
# Usage: eval "$(withtemp [varname [mktempargs]])
#
# If varname is given, a tempfile is generated, its path assigned to the
# variable $varname, and deleted upon exit. Otherwise, no varname
# becomes 'tempfile' and no arguments are passed to mktemp. Varname is
# not exported or local, but you may evaluate using either
#
# $ eval "local $(withtemp ...)"
#
# or
#
# $ eval "export $(withtemp ...)"
#
# If you want either to be applied immediately. Often only the first is
# needed and the second should be followed by a separate export
# statement.
#
# If mktemp args are given, a template is not created from varname.
#
# Upon exit, the tempfile is deleted using 'rm -rf' (since you may have
# passed -d as a mktemp arg.
#
# withtemp attempts to preserve any existing EXIT trap script.
quote() {
if [ $# -eq 0 ]; then
return 0
fi
printf '%q' "$1"
if [ $# -gt 1 ]; then
shift
printf ' %q' "$@"
fi
}
varname="${1:-tmpfile}"
if [ $# -gt 0 ]; then
shift
fi
args="$(quote "$@")"
cat <<EOF
$(quote "$varname")="$(mktemp${args:+ ${args}})"
if [ \$? != 0 ] || [ -n "\${$(quote "$varname")}" ] || [ / = "\${$(quote "$varname")}" ]; then
trap "\$(tl="\$(trap -p EXIT | xargs bash -c 'echo \$3' _)"; echo "\${tl:+\${tl};}")rm -rf \$(printf %q "\${$(quote "$varname")}")" EXIT
else
false
fi
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment