2

I can use mktemp(1) within a shell script to make a temporary file in a directory with a suitable suffix & prefix.

Is there a command that, given a pattern (e.g. NN-output.log) will look for 01-output.log, and if that exists return 02-output.log (or next available number)? I want a command to "get the next sequentially available filename" without having to write that myself in a script.

I know I could use date -Iseconds or similar to get unique, increasing, filenames, but is there anything that'll produce more simplier increasing filenames?

I know it's probably easy to write such a programme, but before I do it myself, I want to see if someone's already done it.

Update Someone asks "how would the script know the pattern?" I'm suggesting that much like mktemp, one would give the pattern to the programme. e.g. "Give me the next file named like output-XX.log" and the programme would look at the X's and fill in 01, look for that file, etc.

  • How would the script know the pattern? Consider file names like file.1.txt 01file, file1, file01, file.one, fileA, filea, Afile etc. It's easy to do for a specific file name style but the general solution is not trivial. That said, yes, getting unique file names is trivial, it just requires a simple shell loop. If that's what you're after, let me know and I can post one. – terdon Apr 3 '16 at 11:45
0

Below is a shell function that's usable with at least ksh and bash. As the comment says, it's hard-coded to expect an input pattern from this particular Question; that is, of the format "XX" (exactly two X's) followed by something -- not (something)-XX as one part of the question implies.

The script uses parameter expansion to strip off the leading XX's to save for later recombination with the increasing n index. It then loops from 1 to 99, zero-pads the number if it needs it, then looks for the non-existence [ ! -f ... ] of such a file. If it does not exist, then it prints that filename and returns successfully (return 0). If it exits the loop without finding an available file, it prints a message to stderr (>&2), prints nothing to stdout, and returns with an unsuccessful return code (return 1).

# hard-coded to expect an input pattern of XX(something)
function rmktemp {
  pattern=$1
  suffix=${pattern#XX}
  n=1
  while [ $n -lt 100 ]
  do
    if [ $n -lt 10 ]
    then
      n="0${n}"
    fi
    tfile="${n}${suffix}"
    if [ ! -f "$tfile" ]
    then
      printf "%s\n" "$tfile"
      return 0
    fi
    n=$((n+1))
  done
  if [ $n -eq 100 ]
  then
    echo Could not find an unused file >&2
    return 1
  fi
}

Use it like:

LOG=$(rmktemp XX-output.log)
[ $? -eq 0 ] && echo stuff > "$LOG"

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.