I use to create a tempfile
, delete it and recreate it as a directory:
temp=`tempfile`
rm -f $temp
#
mkdir $temp
Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.
For a more robust solution i use something like the following. That way the temp dir will always be deleted after the script exits.
The cleanup function is executed on the EXIT
signal. That guarantees that the cleanup function is always called, even if the script aborts somewhere.
#!/bin/bash
# the directory of the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# the temp directory used, within $DIR
# omit the -p parameter to create a temporal directory in the default location
WORK_DIR=`mktemp -d -p "$DIR"`
# check if tmp dir was created
if [[ ! "$WORK_DIR" || ! -d "$WORK_DIR" ]]; then
echo "Could not create temp dir"
exit 1
fi
# deletes the temp directory
function cleanup {
rm -rf "$WORK_DIR"
echo "Deleted temp working directory $WORK_DIR"
}
# register the cleanup function to be called on the EXIT signal
trap cleanup EXIT
# implementation of script starts here
...
Directory of bash script from here.
Bash traps.
The following snippet will safely create a temporary directory (-d
) and store its name into the TMPDIR
. (An example use of TMPDIR
variable is shown later in the code where it's used for storing original files that will be possibly modified.)
The first trap
line executes exit 1
command when any of the specified signals is received. The second trap
line removes (cleans up) the $TMPDIR
on program's exit (both normal and abnormal). We initialize these traps after we check that mkdir -d
succeeded to avoid accidentally executing the exit trap with $TMPDIR
in an unknown state.
#!/bin/bash
# Create a temporary directory and store its name in a variable ...
TMPDIR=$(mktemp -d)
# Bail out if the temp directory wasn't created successfully.
if [ ! -e $TMPDIR ]; then
>&2 echo "Failed to create temp directory"
exit 1
fi
# Make sure it gets removed even if the script exits abnormally.
trap "exit 1" HUP INT PIPE QUIT TERM
trap 'rm -rf "$TMPDIR"' EXIT
# Example use of TMPDIR:
for f in *.csv; do
cp "$f" "$TMPDIR"
# remove duplicate lines but keep order
perl -ne 'print if ++$k{$_}==1' "$TMPDIR/$f" > "$f"
done
My favorite one-liner for this is
cd $(mktemp -d)