Skip to content

January 7, 2011

Zip and copy files from one directory to another with Perl script

Consider the condition some times we need to copy and Zip files from one location to another location everyday. Manually Zipping and copying is a tedious and time consuming process. As the part of automation we can do the same with the help of Perl script to Zip and copy file from one location to another.

In this script we need to specify the $base_path and  backup path $bkp_path. Base path means from where we need to backup the data and backup path means the destination after Zipping wehre we need to move the data (backup media or Backup drive).


use DBI;

use POSIX;
$argc = @ARGV;

if ($argc == 2) {

$base_path = $ARGV[0];

$bkp_path = $ARGV[1];

}else {

print "Usage:perl $PROGRAM <src_path> <dest_path>\n";



opendir(LOGDIR, "$base_path") || print "Could not open directory $base_dir - $!\n";

while (my $entry = readdir(LOGDIR)) {

if ($entry =~ /^\./) {



chdir( $base_path ) or die "Cant chdir to $base_path $!";

if($entry =~ m/.gz/) {

print "The file $entry is already zipped \n";

$zipped_filename = $entry;

} else {

print "The file is $entry \n";

`gzip $entry`;

$zipped_filename = $entry.".".gz;

`mv $zipped_filename $bkp_path`


This script is used to zip files in one directory and move that files to another folder. It will take base path and backup path from command line. Here it is $base_path and $bkp_path. Then it will zip the files in $base_path  and move it $bkp_path.

Suppose the script name is

For e.g. perl /home/praveen/ /home/l3admins/

After running the script you can verify the same in the backup path.

Here $base_path is  /home/Praveen and backup path is /home/l3admins/

You can automate the same with the help of cron tab by putting the following entries,

Consider the cast your Script in the location /root and the Script name is ,

5 6 * * * /root/

According to the above crontab entries the script is scheduled to run everyday at 6.05 AM

Read more from Linux

Leave a comment

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments