How to schedule code backup in Linux shell script and delete older backup files

How to take code/Directory/Files/ backup, schedule to execute automatically and delete delete older backup files.

Below tutorials is about how to take backup of your project’s files on Linux server or system using bash script and how to delete 40 days older files through the shell script.

Linux shell scripting or bash scripting is most helpful scripting languages for Linux server and system admins.
Linux script makes most of the admin task easier.

Here how you can take your projects files backup using shell script on linux server.
It is also advice to keep backup files on Secondary disk and also on remote server incase main server crashes.

Considering below parameters

/var/www/html – Projects directory
/backup – backup directory
/opt/scripts/ – contains backup script
tar – linux utility to archive files
sudoadmin – Project name

Create directories to retain backups files and backup script.

[root@sudoadmin~]#mkdir /backup
[root@sudoadmin~]#chmod 755 /backup
[root@sudoadmin~]#mkdir /opt/scripts
[root@sudoadmin~]#chmod 755 /opt/scripts

To write shell script you can use any cli editor.

[root@sudoadmin~]#vi /opt/scripts/backup.sh

Add below code in /opt/scripts/backup.sh file and modify your “projects folder name” with “sudoadmin”

#!/bin/bash
#author : Hitesh Satarkar
#date:2016-12-05
#purpose: backup sudoadmin code.

#to append date
date=`date +%y%m%d`

cd /var/www/html/
tar -zcf /backup/sudoadmin_code_$date.tgz sudoadmin/

#Delete last 40 days old backup
cd /backup
find . -mtime +40 | grep tgz > temp.txt
for i in `cat temp.txt`
do
rm -f $i
done

rm -f temp.txt

Now schedule “backup.sh” file in crontab to execute every midnight at 1 am and append email for the alert.

[root@sudoadmin~]#crontab -e

0 1 * * * sh /opt/scripts/backup.sh

or

0 1 * * * sh /opt/scripts/backup.sh 2>&1 | mail -s "code backup is executed" serveradmin@example.com

note: to same crontab “Esc then :wq Enter”

Leave a Reply

avatar
  Subscribe  
Notify of