Linux – Automatically generate filename using bash

bashfile managementlinux

Let's assume i have such files:

out-1.avi

I want to have a piece of bash code which will give me the next filename for such list:

out-1.avi
out-2.avi
out-3.avi
etc.

Edit The thing i need to achieve is to get next filename for webcam recording script so it wont ovewrite!

Best Answer

I don't know the context, but the following loop contains all the elements you will need:-

n=0; while (($n < 10)); do ((++n)); echo name=out-$n.avi; done

This will list the first 10 files in your sequence.

After your edit, I see several answers.

A simple modification of my original loop would be:-

n=1; while [ -f out-$n.avi ]; do ((++n)); done; echo name=out-$n.avi

This will work well for a few files, but becomes increasingly inefficient as the number of files mounts into the hundreds.

A more efficient answer would be to save the latest file number in its own file:-

n=`line<avicount.text`; ((++n)); echo "$n">avicount.text; echo name=out-$n.avi

This script will generate a new name each time it is called, but relies on avicount.text remaining always in synchronisation with the files and names in use.

A better solution all round would be to use a time stamp instead of a sequence number:-

echo name=out-`date +%Y%M%d%H%m%S`.avi

This will give a unique name based on the second when the script is called, and it can be useful to have a file's creation time included in its name. This scheme also allows for files to be deleted, archived or otherwise moved at will, without affecting future file names.

Related Question