Create new file but add number if filename already exists in bash

heltonbiker picture heltonbiker · Aug 30, 2012 · Viewed 45k times · Source

I found similar questions but not in Linux/Bash

I want my script to create a file with a given name (via user input) but add number at the end if filename already exists.

Example:

$ create somefile
Created "somefile.ext"
$ create somefile
Created "somefile-2.ext"

Answer

choroba picture choroba · Aug 30, 2012

The following script can help you. You should not be running several copies of the script at the same time to avoid race condition.

name=somefile
if [[ -e $name.ext || -L $name.ext ]] ; then
    i=0
    while [[ -e $name-$i.ext || -L $name-$i.ext ]] ; do
        let i++
    done
    name=$name-$i
fi
touch -- "$name".ext