Friday, March 23, 2007

Captain's Log, Stardate date +%Y%m%d


How do you get the current date to use in a Linux / Unix shell script?

Take a look at this simple backup script:
----------------------------------------------------

#!/bin/sh

export FILE_DATE=`date +%Y%m%d`

export backup_file=backup_${FILE_DATE}.tgz

[ ! -d /opt/backups ] && mkdir -p /opt/backups

tar -zcvf /opt/backups/${backup_file} /var/named

----------------------------------------------------

What does that FILE_DATE variable do for me?

Well, let's try it on the command line.

bash-2.05b$ export FILE_DATE=`date +%Y%m%d`
bash-2.05b$ echo $FILE_DATE
20070323

Ah, so that's how we get the current date in a usable format. This method makes the files sortable later. Of course, if you need more than one backup per day, you can always add more date options.

Notice a few things about this method of scripting.

1) export, is optional, but it makes the environmet variable available to other scripts.
2) backticks ` are not to be confused with single quotes '
3) variables can be combined with text, or even become part of another variable. Not the ${} to enclose the variable name. The characters are optional when the variable is separated by spaces, but in this case, the variable is part of a string of text.

4) Note the common sysadmin trick of a one line if statement. Rather than using "if", we use the double ampersand "&&". This is interpreted as If the stuff in the brackets [ ] is true, then do the stuff on the right. So, basically, if there is no /opt/backups directory, then make one.

So what does the file look like when we run the script?

If you run it on March 23, 2007, it would look like this

/opt/backups/backup_20070323.tgz

In this example, we are just backing up /var/named, which is helpful for a DNS server, so you will have to modify as needed. The idea is just to show a few scripting techinques.


- scottm

No comments: