This project provides an automated backup solution using a Bash script (backup.sh). The script archives and compresses files from a source directory and moves the backup file to a specified destination directory. Additionally, a cron job can be set up to automate backups at scheduled intervals (Daily at midnight).
- Takes two arguments: the source directory (to back up) and the destination directory (to store the backup).
- Creates a compressed
.tar.gzarchive of the source directory. - Moves the backup file to the destination directory.
- Can be scheduled to run automatically using a cron job.
Run the following command to clone the repository:
git clone https://github.com/DenethSachintha/cronjob-automated-backup.git
cd cronjob-automated-backupBy default, scripts are not executable. To allow execution, run:
chmod +x backup.shYou can check if backup.sh is executable using:
ls -l backup.shExpected output:
-rwxr--r-- 1 user user 1221 Mar 14 11:58 backup.sh
rwx means the owner has read, write, and execute permissions.
touch source_directory/any.txtThis creates a dummy file (any.txt) inside the source_directory to test the backup process.
Execute the script by specifying the source and destination directories:
./backup.sh source_directory destination_directoryExpected output:
targetDirectory: source_directory
destinationDirectory: destination_directory
Backup created: backup-YYYY-MM-DD_HH-MM-SS.tar.gz
Backup moved to: destination_directory/backup-YYYY-MM-DD_HH-MM-SS.tar.gz
crontab -eTo schedule a backup to run daily at midnight, add the following line:
0 0 * * * /usr/local/bin/backup.sh /home/project/source /home/project/dest
Explanation:
| Field | Value | Meaning |
|---|---|---|
| Minute | 0 |
0th minute |
| Hour | 0 |
0th hour (midnight) |
| Day of Month | * |
Every day |
| Month | * |
Every month |
| Day of Week | * |
Every day of the week |
This ensures that backup.sh runs at midnight every day.
mkdir directory_nameCreates a new directory with the specified name.
sudo service cron startStarts the cron job scheduler, ensuring that scheduled tasks run as expected.
sudo service cron stopStops the cron job scheduler, preventing scheduled tasks from executing.
sudo service cron statusDisplays whether the cron service is running or stopped.
With this setup, you can automate your backups using backup.sh and ensure that your data is archived regularly. You can modify the cron job timing as per your needs and integrate this script into larger automation workflows.