What's the difference between tempfile and mktemp?

前端 未结 3 1477
我在风中等你
我在风中等你 2021-02-03 21:38

Most systems I\'ve encountered have both tempfile(1) and mktemp(1). There are syntactic differences, and mktemp can also create directorie

相关标签:
3条回答
  • 2021-02-03 22:24

    I suspect there's some interesting Unix lore behind this ...

    The history of mktemp can be traced to OpenBSD 2.1. However, it became a part of GNU coreutils much later. This post announced the inclusion of mktemp for coreutils.

    Until then, tempfile was being used by a number of programs. There was also a proposal to make tempfile a wrapper around mktemp, which was rejected to discourage use of tempfile.

    However, the following was added to tempfile manual:

    Exclusive creation is not guaranteed when creating files on NFS partitions. tempfile cannot make temporary directories. tempfile is deprecated; you should use mktemp(1) instead.

    0 讨论(0)
  • 2021-02-03 22:41

    From the source code sight of things (on debian) tempfile is from the package debianutils and uses the libc function tempnam() while mktemp is from GNU coreutils and doesn't use the libc function

    0 讨论(0)
  • 2021-02-03 22:42

    It says in tempfile's manual that:

    tempfile - create a temporary file in a safe manner

    While in mktemp:

    mktemp - create a temporary file or directory

    They're probably just almost the same, only that the implementation is a little different.

    As said in the manual, tempfile actually has some precautions like:

    a) In case the environment variable TMPDIR exists and contains the name of an appropriate directory, that is used.

    b) Otherwise, if the --directory argument is specified and appropriate, it is used.

    c) Otherwise, P_tmpdir (as defined in <stdio.h>) is used when appropriate.

    d) Finally an implementation-defined directory (/tmp) may be used.

    It's actually useful if the script trusts mktemp or tempfile enough that it's certain that a temporary file or directory would be created. But I don't see much problem just using mktemp if you run precautions in your script yourself. You can use [ -e ], [ -f ], [ -d ], [ -L ], etc. to verify if a file could actually be made/was already made. Even check if something's writable, readable, and/or executable with -r, -w and -x. In bash, see help test.

    Still for the sake of continuous runtime perhaps you would better rely on tempfile when running your code in multiple environments. Just make sure that it's available everywhere enough. With which or with type -P you could check which one of them is available. An example:

    create_temp() {
        if type -P tempfile >/dev/null; then
            # use tempfile based from $1
        elif type -P mktemp > /dev/null; then
            # use mktemp based from $1
        else
            echo "Can't find temporary file creator."
            exit 1
        fi
    }
    
    0 讨论(0)
提交回复
热议问题