This is one of the most usefull examples: a
script which does b ackup. I am going to do something really simple.
We have a file with data (for example: data.txt), which changes, because everyday users edit it. The file also might be a complex database file (the Firebird, the SQLite), a document in the Microsoft Word or Microsoft Excel. It does not matter currently.
For us, the interesting thing is the c
hange. If a file is frequently changed, the file must be saved everyday in case of someone had recalled that 2 weeks ago and written some very important information to the file and removed them one day later.
We use a will simple rule for writing the scripts: We do some actions handmade first, and later we will write the script which will do the same automatically.
We check nice command „date“ first. The command will generate a suffixes for us to recognize which backups were enerated on some day. In this example, the suffix will be a date in form like YYYY-MM-DD, so backups will be named for example: data.txt.2012-01-02, data.txt.2012-01-03, etc…
localhost$ date +%Y-%m-%d 2012-04-10
Also, we need to know a very difficult command to copy files (;-P) for example:
localhost$ cp /path/to/data.txt /backup_dir/data.txt.2012-04-10
In this way we created a simple script for everyday backup of the file. Of course our suffix has a sense when we do backups once a days. If you know the date command, you can create you own suffixes which may contain a hour, a minute or a second, so then
you can backups more times than once a day. It’s up to you.
Here is code of the entire script:
#!/bin/bash ### Path to the cp command - it looks like strange, but it's good ### practice if your script may working on many linux distributions CP="/bin/cp" ### Backup's suffix - actual date in format YYYY-MM-DD ### The suffix is result of the date command so we need use `` ### apostrophes DATA=$(date +%Y-%m-%d`) ### Path to the file which is copying DANE="/path/to/data.txt" ### Path to the destination backup dir and backup's file name BACKUP="/backup_dir/data.txt.$DATA" ### Does file exist? if [ -e "$DANE" ]; then echo "$DANE} is found, doing backup..." $CP "$DANE $BACKUP" fi
If this script will run once a time on many days then we will have the following file list:
data.txt.01-03-2012 data.txt.02-03-2012 data.txt.03-03-2012 data.txt.04-03-2012 data.txt.05-03-2012 data.txt.06-03-2012 data.txt.07-03-2012 data.txt.08-03-2012 data.txt.09-03-2012 data.txt.10-03-2012 data.txt.11-03-2012 data.txt.12-03-2012 data.txt.13-03-2012 data.txt.14-03-2012 data.txt.15-03-2012 data.txt.16-03-2012 data.txt.17-03-2012 data.txt.18-03-2012 data.txt.19-03-2012 data.txt.20-03-2012 data.txt.21-03-2012 data.txt.22-03-2012 data.txt.23-03-2012 data.txt.24-03-2012 data.txt.25-03-2012 data.txt.26-03-2012 data.txt.27-03-2012 data.txt.28-03-2012 data.txt.29-03-2012 data.txt.30-03-2012 data.txt.31-03-2012
Leave a Reply
You must be logged in to post a comment.