In this tutorial you will learn about the Linux Shell Script For Database Backup and its application with practical example.
In this tutorial, I’ll show you how to backup database using shell script linux. We will learn with the help of example of linux shell script for database backup. In this example, I just created a MySQL shell script that I use on my Linux servers to make database backups with mysqldump.
Linux Shell Script For Database Backup
Create .sh File
In this step, We will create a database_backup directory in server home directory. Now we will create a hell script file backup.sh in database_backup folder. Let’s open backup.sh file and put the following code in it.
/home/database_backup/backup.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
username=username password=password database=your_database_name now="$(date +'%d_%m_%Y_%H_%M_%S')" filename="db_backup_$now".gz backupfolder="/home/database_backup/" fullpathbackupfile="$backupfolder/$filename" logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt echo "mysqldump started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile" mysqldump --user=$username --password=$password $database > $fullpathbackupfile echo "mysqldump finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile" echo "remove backup 5 days old" >> "$logfile" # Delete files older than 5 days #find $backupfolder=/* -mtime +5 -exec rm {} \; echo "complete removing" >> "$logfile" exit 0 |
Executable .sh File
1 2 3 4 5 |
run .sh file sudo chmod +x backup.sh sudo ./backup.sh |
Setup Crontab
In the last step, we will setup a cron job for backup.sh file in crontab. Let’s open crontab file using below command:
1 |
crontab -e |
Add below line in crontab file to run the shell script to take laravel database backup.
1 |
0 2 * /home/database_backup/backup.sh |