Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 ;

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

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;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.