Last active
August 29, 2015 13:56
-
-
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`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
# ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OS X has had
mktemp -d
for a long time (2005?) but it's the BSD variant which requires a template argument to-d
: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.