increment directory name in bash

bash, date, linux

Solution

You can use the following script:

#!/bin/bash

date=$(date +"%d%m%Y")
n=1

# Increment $N as long as a directory with that name exists
while [[ -d "/home/files/${date}-${n}" ]] ; do
    n=$(($n+1))
done

mkdir "/home/files/${date}-${n}"

Note that the script isn't safe against race conditions, meaning you cannot use it in an environment where many concurrent processes calling the script at the same time.

Problem

I have a bash script whereby i'd like to create a directory with the date and an incremental number upon every boot using date ``` DATE=$(date +"%d%m%Y") ``` I'd like the output to be 300514-1 then after a reboot 300514-2 and so on but the files need to be stored into that directory that was created ie ``` SAVEDIR=/home/files/$DATE-* ```

Original source