Skip to content

Instantly share code, notes, and snippets.

@rcrowley
Last active August 29, 2015 13:56
Show Gist options
  • Save rcrowley/8813643 to your computer and use it in GitHub Desktop.
Save rcrowley/8813643 to your computer and use it in GitHub Desktop.
A protip for authors of shell programs. I use this pattern *all the time* for working in a temporary directory and cleaning it up after I'm done but a quirk in how shells interpret failures in command substitution caused a program like these to remove my coworker's home directory when he ran said program on Mac OS X, which doesn't have `mktemp -d`.
set -e
# Looks clever, is short, but removes your working directory on Mac OS X
# where `mktemp -d` fails.
cd "$(mktemp -d)"
trap "rm -rf \"$PWD\"" EXIT INT QUIT TERM
# ...
set -e
# Is longer, is named terribly, but at least it doesn't fail by removing
# your home directory.
TMP="$(mktemp -d)"
cd "$TMP"
trap "rm -rf \"$TMP\"" EXIT INT QUIT TERM
# ...
@acdha
Copy link

acdha commented Feb 4, 2014

OS X has had mktemp -d for a long time (2005?) but it's the BSD variant which requires a template argument to -d:

mktemp -d /tmp/foobarXXXX

That said, this is a great general cautionary point – there's no reason not to use the second form worth the risk of getting it wrong.

@nbrownus
Copy link

nbrownus commented Apr 8, 2015

Remember when this happened to me? ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment