2

How can we obtain a temporary file name in a standard-conforming shell script (using no commands or extensions which are not described the 2013 edition of IEEE 1003.1).

There doesn't appear to be any utility for generating a temporary filename, only C library functions.

1

Not easily.

You can get a (deleted) temp file and have a fd open on it with:

exec 3<<EOF
whatever
EOF

But you can't write to it later on and there's no command that can make you seek back on a fd.

You can try and implement it manually:

mktemp() (
  prefix=$1
  i=0; suffix=
  set -C
  until
    file=$prefix$suffix
    error=$({ : > "$file"; } 2>&1)
  do
    if [ ! -e "$file" ] && [ ! -L "$file" ]; then
      # that probably failed for another reason than noclobber. Give up.
      printf >&2 'Cannot create "%s": %s\n' "$file" "$error"
      return 1
    fi
    i=$(($i + 1))
    suffix=.$i
  done
  printf '%s\n' "$file"
)

If you want some randomness in the filename, awk's got a rand() which you can use with printf("%c").

Best is to avoid temp files if possible. Bear in mind that their clean-up is almost as much a pain as their creation.

0

Temporary files are a security problem only if one creates them in a shared directory such as /tmp or /var/tmp. To create temp file in a safe and secure way, just place it in a directory, like the user's home directory, where other users do not have write permission. For example:

tmpname=$HOME/.deleteme$$
some_command >"$tmpname"

By using a non-shared directory, all the issues of race conditions go away. (If an attacker already has write access to your home directory, then you are pwned and the attacker has no need to play with temp files and race conditions.)

To make sure that the temp file is deleted, create a trap

trap 'rm -f "$tmpname"' EXIT

The trap statement should be placed in the script before the temp file is created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.