Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 8 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
Does not work in a script (not waiting between) - I tried touch test$(date +%Y%m%d-%H%M%S) ; touch test$(date +%Y%m%d-%H%M%S), it created only one file. Nanoseconds-time works: touch test$(date +%Y%m%d-%H%M%S%N) ; touch test$(date +%Y%m%d-%H%M%S%N) and touch test$(date +%Y%m%d-%H%M%S%N) test$(date +%Y%m%d-%H%M%S%N) create two files each. – Volker Siegel Sep 26 '14 at 1:57

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
    if [[ -e "$file" ]]; then
      touch "$file"

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

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

Your Answer


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.