Lurch
Lurch

Reputation: 875

increment directory name in bash

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-*

Upvotes: 2

Views: 3683

Answers (2)

hek2mgl
hek2mgl

Reputation: 158080

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.

Upvotes: 9

David W.
David W.

Reputation: 107060

Take a look at mktemp. It won't do exactly what you want, but it will guarantee that your directory names will be unique and you won't run into any sort of race conditions.

Upvotes: 0

Related Questions