Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
# ...

This comment has been minimized.

Copy link

@acdha 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.


This comment has been minimized.

Copy link

@nbrownus 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