cortman
January 18th, 2012, 03:03 PM
I'm still getting my feet wet in bash scripting, and was working, just for fun, on a simple backup script the other evening.
As a test, I'm trying to copy a file called "doug" in my home to the /data/backup folder.
/data is a separate NTFS partition on my HD that I use for storage.
My goal is to have the script look in /data, and if there is a folder called "backup" in it already, rename it "backup.old", create a new "backup" folder, and copy /home/cortman/doug into it.
If there is no folder on /data called backup, I want it to create one and copy /home/cortman/doug into it.
if [ -d /home/cortman/data/backup ] ;
then
mv /home/cortman/data/backup backup.old ;
mkdir /home/cortman/data/backup ;
cp /home/cortman/doug /home/cortman/data/backup ;
else
mkdir /home/cortman/data/backup ;
cp /home/cortman/doug /home/cortman/data/backup ; fi
The problem:
I run it once, with no existing backup folder. It works great.
I run it a second time. It copies the old ~/data/backup folder into my main ~/ folder and renames it backup.old, and makes a new backup folder in ~/data.
I run it a third time. Now it moves the old ~/data/backup folder into ~/backup.old, and makes a new backup folder in ~/data.
I run it a fourth time, and get an error-
mv: cannot move `/home/cortman/data/backup' to `backup.old/backup': Directory not empty
mkdir: cannot create directory `/home/cortman/data/backup': File exists
Sorry if tl;dr, or if I'm doing it all wrong or missing something totally obvious. Any input would be greatly appreciated!
As a test, I'm trying to copy a file called "doug" in my home to the /data/backup folder.
/data is a separate NTFS partition on my HD that I use for storage.
My goal is to have the script look in /data, and if there is a folder called "backup" in it already, rename it "backup.old", create a new "backup" folder, and copy /home/cortman/doug into it.
If there is no folder on /data called backup, I want it to create one and copy /home/cortman/doug into it.
if [ -d /home/cortman/data/backup ] ;
then
mv /home/cortman/data/backup backup.old ;
mkdir /home/cortman/data/backup ;
cp /home/cortman/doug /home/cortman/data/backup ;
else
mkdir /home/cortman/data/backup ;
cp /home/cortman/doug /home/cortman/data/backup ; fi
The problem:
I run it once, with no existing backup folder. It works great.
I run it a second time. It copies the old ~/data/backup folder into my main ~/ folder and renames it backup.old, and makes a new backup folder in ~/data.
I run it a third time. Now it moves the old ~/data/backup folder into ~/backup.old, and makes a new backup folder in ~/data.
I run it a fourth time, and get an error-
mv: cannot move `/home/cortman/data/backup' to `backup.old/backup': Directory not empty
mkdir: cannot create directory `/home/cortman/data/backup': File exists
Sorry if tl;dr, or if I'm doing it all wrong or missing something totally obvious. Any input would be greatly appreciated!