[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: mktemp and suffixes

From: Bob Proulx
Subject: Re: mktemp and suffixes
Date: Mon, 22 Mar 2010 18:03:55 -0600
User-agent: Mutt/1.5.18 (2008-05-17)

Nuno J. Silva wrote:
> In a BASH script I'm writing, I need temporary files. Unfortunately, not
> only some of the used programs don't accept stdin nor stdout, but they
> also require "extensions" on the input/output file.

Yep.  A common problem.

> As I want to be sure nothing is overwritten, I tried calling mktemp with
> a modified template:
> $ mktemp tmp.XXXXXXXXXX.ext
> mktemp: too few X's in template `tmp.XXXXXXXXXX.ext'

Beware that different mktemp implementations behave different.  Some
implementations will not produce an error but since the X's are not on
the right the filename produced will not be unique.

  $ mktemp /tmp/tmp.XXXXXXXXXX.ext
  $ ls -ldog /tmp/tmp.XXXXXXXXXX.ext
  -rw------- 1 0 2010-03-22 17:50 /tmp/tmp.XXXXXXXXXX.ext
  $ mktemp /tmp/tmp.XXXXXXXXXX.ext
  ...blocks trying to create a unique file...

Not what you want.

> Is this a limitation of mktemp (X's must be on the right)?

Yes.  It is a legacy limitation.  As Jim mentioned a feature for this
was recently added to GNU coreutils.

The traditional way to handle this problem was to create a temporary
directory and then create files with suffixes inside the directory.
Because the directory is uniquely named you can use a known name for
the file within the directory.

This is off of the top of my head, untested, I am not responsible for
any problems with it, and may contain a mistake and so forth but you
might try something like this example.  This is a do-nothing but with
enough to hopefully show you the technique.

  unset tmpdir
  trap 'cd / ; rm -rf $tmpdir' EXIT
  tmpdir=$(mktemp -d) || exit 1
  cd $tmpdir || exit 1
  echo foo > file1.ext
  sed 's/foo/bar/' file1.ext > file2.ext
  cat file2.ext
  ls -log
  exit 0


reply via email to

[Prev in Thread] Current Thread [Next in Thread]