Backup a folder daily with Shell script

Create a Script for backup a folder in Linuxmotpc.com

Storage: Backup Your Files | Information Technology Services | Binghamton University

Introduction

Backing up crucial data is an essential aspect of maintaining system reliability and safeguarding against unforeseen events in a Linux environment. Creating a robust backup system ensures the protection of vital information stored within a system. In Linux, the process of backing up a folder can be streamlined and automated using shell scripts. These scripts offer a flexible and efficient way to archive and safeguard directories, enabling users to tailor the backup process to their specific needs. By harnessing the power of shell scripting, users can construct automated routines that replicate and secure important data, providing an added layer of resilience against potential data loss scenarios.

Shell Script

  • The Idea is to backup a folder from 2 days ago and just keep 2 backup file.
  • The Backup folders will be compressed and then move to backup destination folder.
  • In the source folder, there is serial folder with name is the day it been generated.

#!/bin/bash

# Source folder
source_dir="/opt/nsp"

# Backup destination folder
backup_dir="/opt/backup"

# Number of days you need to backup (2 days ago)
backup_date=$(date -d "2 days ago" '+%Y%m%d')

# Backup file's name
backup_file="${backup_dir}/backup_$backup_date.tar.gz"
echo "backup_file=$backup_file"

# Maximum number of files you want to keep
max_backups=2

# Create new compress file
tar -czvf "$backup_file" -C "$source_dir" ./$backup_date

# Delete source folder that have been backup
#find "$source_dir" -type d -name $backup_date -exec rm -r {} +

# List of the compressed file and arrange in time ( new - old )
backup_files=($(ls -t $backup_dir/backup_*.tar.gz))

# Check the number of compressed files
backup_count=$(ls -t $backup_dir/backup_*.tar.gz | wc -l)

# If the number of compressed files are over max_backups then delete the old files
if [ $backup_count -gt $max_backups ]; then
ls -t $backup_dir/backup_*.tar.gz | tail -n $[$backup_count - $max_backups]|xargs rm -rf
fi

Deploy by Cron

Step 1: Create a script file and name it to .sh

touch /root/backup_script.sh

vi /root/backup_script.sh

#Add above script to the file

 

Step 2: Change the permission

chmod +rwx backup_script.sh

 

Step 3: Add script to Crontab and run daily

crontab -e

#Run it everyday at 00:00

0 0 * * * /root/backup_script.sh

Hope you will successfully backup your folder!
Source: motpc.com

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
0
Rất thích suy nghĩ của bạn, hãy bình luận.x
()
x