Search code examples
shelldatetimecross-platformposixtemporary-files

shell: how to create a unique temporary file path cross-platform/portable?


How to create a unique file path in a shell cross-platform? I have looked around on most of the answers and it seems that no cross-platform/portable solution is simple enough. mktemp seems to be the most solid alternative on platforms where mktemp is availible. When it is not availible /dev/random on this stackoverflow question can also be an alternative. If some kind of time traceability is wanted then what would be the next alternative?


Solution

  • The most simple that is included in the posix standard is to use mktemp. If that is not availible date is the next second option. %s parameter of date may also not be availible on all legacy platforms.

    date "+%s-%N"
    

    %s seconds since epoch and %N nano seconds to be dead sure of the uniqueness.

    With more context:

    TEMPDIR=/tmp/`date "+%s-%N"`