heltonbiker heltonbiker - 1 month ago 14
Linux Question

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

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"


Thanks for reading

Answer

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 ]] ; then
    i=0
    while [[ -e $name-$i.ext ]] ; do
        let i++
    done
    name=$name-$i
fi
touch $name.ext
Comments