2

I'd like to copy a file to a temporary location.

I'd like to make sure I'm not overwriting anything important, and that I know the location of the file while the script is running.

#!/bin/bash

myfile="$(mktemp)"
cp "source" "$myfile"

# work with $myfile

rm "$myfile"

Does this seem OK? Is there anything I'm missing? (Permissions, etc.?)
I have a bad feeling about overwriting that file.

user
  • 339
  • 1
  • 4
  • 13

1 Answers1

4

From the man page

Create a temporary file or directory, safely, and print its name.

You could add a check for whether mktemp was successful.

myfile="$(mktemp)"
if test $? != 0; then
  exit 1
fi

If mktemp succeeds, it has created a file that was not present before. You can safely overwrite that file, that is the purpose for using mktemp. The permissions are set to u+rw, as mentioned in the manual.

RalfFriedl
  • 8,816
  • 6
  • 23
  • 34