Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I was wondering if it was possible have a command that creates one file, but every time the command is executed, it wouldn't overwrite the file created in the previous execution.

For example: touch test1.txt would create 1 file called test1.txt. But the next time I execute it, I would like the new file to be called test2.txt, or something like that. So without overwriting the already existing file. In a way it could be executed multiple times without problems.

Don't misunderstand me, I'm not trying to create multiple files with one command.

Thanks in advance!

share|improve this question

3 Answers 3

up vote 7 down vote accepted

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.

share|improve this answer
    
This is just what I was looking for, thanks! :) –  Nick Lemaire Aug 2 '11 at 15:53

If sequence numbers are not required, then the easiest way is to use mktemp command.

share|improve this answer
    
mktemp generates a random, unique filename, using a template. You'd likely capture the output of mktemp in a variable. From linuxmanpages: TMPFILE=$(mktemp /tmp/example.XXXXXXXXXX) || exit 1 echo "program output" >> $TMPFILE –  bgvaughan Aug 8 '11 at 0:08
    
Another common method is to use the current process id, from the shell variable $$: TMPFILE='/tmp/tmp.$$'; touch $TMPFILE –  bgvaughan Aug 8 '11 at 0:15

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.

share|improve this answer
    
brilliant, great function. –  Marco Ceppi Aug 2 '11 at 16:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.