Command line: create file with new filename if the filename already exists

The easiest solution would be to add a timestamp to the filename and not use a single digit.

The easiest method to create an empty file would be touch test$(date +%Y%m%d-%H%M%S) and that would result in a file named test20110802-170410. A 2nd time test* will get a newer timestamp so it will result in 2 files.


I doubt a general command exist to do that, but you can think of something like this:

create() {
  read prefix number suffix < <(sed -r 's/(.*)([0-9]+)\.(.*)$/\1 \2 \3/' <<<"$1")
  while true; do
    file="$prefix$number.$suffix"
    if [[ -e "$file" ]]; then
      ((number++))
    else
      touch "$file"
      break
    fi
  done
}

The input parameter to the function is split in prefix, number, suffix, then until the file exists, the number is incremented. Found a free slot, the file is created with touch.

The split mechanism should be adapted to your needs, and various error check should be added.