Search notes:

Shell command: mktemp

mktemp creates temporary files (temp-files) or directories beneath the directory specified by the environment variable $TMPDIR if set or /tmp otherwise.

Create a temporary file

mktemp creates a temporary file and returns its filename.
The file is not automatically destroyed when the process ends.
FILENAME=$(mktemp)

if [ -f $FILENAME ]; then
  echo "Temporary file $FILENAME exists"
else
  echo "Temporary file $FILENAME does not exist"
fi
Github repository shell-commands, path: /mktemp/temp-file.sh

Create a temporary directory

With the -d flag, a temporary directory is created and its filename returned.
DIRECTORY=$(mktemp -d)

if [ -d $DIRECTORY ]; then
  echo "Temporary directory $DIRECTORY exists"
else
  echo "Temporary directory $DIRECTORY does not exist"
fi
Github repository shell-commands, path: /mktemp/d_create-temporary-directory.sh

Running dry (without creating anything)

The mktemp commands can be compbined with -u which only returns a (possible) temporary file or directory name without creating it.
FILENAME=$(mktemp  -u   )
DIRECTORY=$(mktemp -u -d)

if [ -e $FILENAME ]; then
  echo "$FILENAME does not exist"
else
  echo "$FILENAME exists"
fi

if [ -e $DIRECTORY ]; then
  echo "$DIRECTORY does not exist"
else
  echo "$DIRECTORY exists"
fi
Github repository shell-commands, path: /mktemp/u_dry-run.sh
Note: the value of $FILENAME and $DIRECTORY have no indication whether they refer to a file or directory.

Using a pattern

mktemp can be invoked with a pattern (template) consisting of at least 3 consecutive X. The X
print_random_name() {

  pattern=$1
  file_created=$(mktemp $pattern)

  printf "%-20s -> %s\n" $pattern $file_created

# Remove file that was created by mktemp
  rm $file_created
}

# Replace X's with random letters
print_random_name foo-XXXX-bar

# Only last group of X's are replaced
print_random_name abc-XXXX-def-XXXX
Github repository shell-commands, path: /mktemp/files-with-random-names.sh

See also

Shell commands

Index