1

I'm looking to configure this backup script to take the current day's date and make the directory in a mmddyyyy format, as this will be automated. However, if the directory with that current day already exists (if I needed to do more than one backup on a given day), I want to add -1 or -2, so that it would appear 07072011-3 (if it were the 4th backup being made that day).

is there a simple way to add onto the end of the directory name, +1 for each time it's been written?

Set date/folder name

today="$ (date +%m%d%Y)"

mkdir /home/user/backup/$today

Check if dir exists

if [ ! -d /home/user/backup/$today ]

then

echo Directory already exists ;

koo
  • 23
  • 3

2 Answers2

1

Do you have to use DDMMYYYY ? Using YYYYMMDD is easier as the default sort order for ls will then correctly sort the newest to the top.

You can also extend the date idea to use time e.g.

today=$( date +%Y%m%d%H) 

to get YYYYMMDDHH and you can even add %M and %S if you need to.

user9517
  • 114,104
  • 20
  • 206
  • 289
1

If you really want to stick with the format you have selected, you could do something like the following:

today=$(date +%Y%m%d)
folder=$today
i=0
while [ -e /home/user/$folder ]
do
  echo "${folder} exists";
  i=$(( $i + 1 ))
  folder="${today}-${i}"
done
echo $folder;
cyberx86
  • 20,620
  • 1
  • 60
  • 80