What's the difference between tempfile and mktemp?

前端 未结 3 1478
我在风中等你
我在风中等你 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: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 ) 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
    }
    

提交回复
热议问题