简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM