Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All

I am trying to create a very simple backup script that will tar specified directories. The directories need to be configurable i.e not coded into the tar command, and the file backups need to be given a name and date in the format of DDMMYYYY.

So, if there was some kind of array or something with the directorys i want backed up in it e.g /home, /var/spool/mail, /etc/postfix, /etc/httpd the script would create tar.gz files for each one of these directories and name them home-07052003.tar.gz, mail-07052003, postfix-07052003.tar.gz, httpd-07052003.tar.gz

Help much appreciated. Cheers

Replies are listed 'Best First'.
Re: Simple Backup Script
by pzbagel (Chaplain) on May 07, 2003 at 16:01 UTC

    Here is a shell script, it assumes your directory list is in a file called dirlist which can be changed easily.

    #!/bin/sh date=`date +%d%m%Y` for x in `cat dirlist` do y=`basename $x` tar zcvf $y-${date}.tar.gz $x done

    The same basic structure can be rewritten in perl or you can go the whole Archive::Tar route and really make it complex:D

    Good luck

      Or, without a static list file:
      #!/bin/sh date=`date +%d%m%Y` for x in $* <---- here's the only change needed! do y=`basename $x` tar czvf $y-${date}.tar.gz $x done
      You could even make this a shell function in your .bash_profile or .bashrc, like so:
      function maketar { date=`date +%d%m%Y` for x in $* ; do y=`basename $x` tar czvf $y-${date}.tar.gz $x done } export -f maketar
      There's (wait for it!) "More Than One Way To Do It." Even before you get into doing it in Perl. :)
Re: Simple Backup Script
by hardburn (Abbot) on May 07, 2003 at 15:50 UTC

    Any reason why this must be done in Perl? A simple shell script should do the job quite nicely.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      No reason i guess, i have never wrote a shell script before tho :(

        While there are some complex things you could do with it, for this problem, you shouldn't need much more than writing out the same commands you would give on a command line, plus a few variables.

        #!/bin/sh date=`date +%Y%m%d%k%M%S` path=$1 # Path to use is given on the command line # Use last directory in ${path} as the filename to save # to. (Could use awk or something else here, but I'm # more familer with Perl). # save_file=`perl -e '$file=pop; $file=~m!/(.*)$!; print $1' ${path}` tar -zxf ${save_file}-${date}.tar.gz ${path}

        ----
        I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
        -- Schemer

        Note: All code is untested, unless otherwise stated