Home

Bash Shell Scripts - Creating an Automated Backup

Overview

I created a bash script that automated the backup of a folder. The script generates a compressed archive of the CompanyA folder with a timestamped filename.

Task 2: Write a shell script

In this task, I created a Bash shell script that automates the creation of a backup of the CompanyA folder as a compressed archive. The name of the archive was in the format date of the day-backup-companyA.tar.gz.

Important to know

I had to use sudo to complete this task as I was not root.

To validate that I was in the home folder, I entered the following command:

pwd

Output:

/home/ec2-user/

To create a generic shell script called backup.sh, I entered the following command:

touch backup.sh

To change the file privileges to make backup.sh be executable, I entered the following command:

sudo chmod 755 backup.sh

I used vi text editor to open the backup.sh file for editing:

vi backup.sh

To activate insert mode, I entered i

On line 1 of the script, I entered #!/bin/bash to add the shebang line, and pressed Enter to go to the next line.

To create a variable for the current date, I entered:

DAY="$(date +%Y_%m_%d_%T_%H_%M)"
You can use the date +%Y%m%d command to retrieve the current date and time. This command formats this information as follows: 2021_08_31

To create a variable for the backup file for the day, I entered:

BACKUP="/home/$USER/backups/$DAY-backup-CompanyA.tar.gz"
$USER returns the current user, which is ec2-user. This is the equivalent of entering the whoami command in the shell. The created archive will be located in /home/ec2-user/backups.

On the next line, I entered:

tar -csvpzf $BACKUP /home/$USER/CompanyA

Contents of backup.sh script written so far:

#!/bin/bash DAY="$(date +%Y_%m_%d)" BACKUP="/home/$USER/backups/$DAY-backup-CompanyA.tar.gz" tar -csvpzf $BACKUP /home/$USER/CompanyA

With my current text editor, I saved my script and exited from the editor by pressing the Esc key, entering :wq and pressing Enter.

To run backup.sh, I entered the following command:

./backup.sh

Output:

tar: Removing leading `/' from member names /home/ec2-user/CompanyA/ /home/ec2-user/CompanyA/Management/ /home/ec2-user/CompanyA/Management/Sections.csv /home/ec2-user/CompanyA/Management/Promotions.csv /home/ec2-user/CompanyA/Employees/ /home/ec2-user/CompanyA/Employees/Schedules.csv /home/ec2-user/CompanyA/Finance/ /home/ec2-user/CompanyA/Finance/Salary.csv /home/ec2-user/CompanyA/HR/ /home/ec2-user/CompanyA/HR/Managers.csv /home/ec2-user/CompanyA/HR/Assessments.csv /home/ec2-user/CompanyA/IA/ /home/ec2-user/CompanyA/SharedFolders/

To verify that the archive was created in the backups folder, I entered the following command:

ls backups/

Output:

2022_05_18_05:55:28_05_55-backup-CompanyA.tar.gz

I learned that I can schedule this type of script via cron to create a daily backup of the folder. I could also use other commands to copy this archive to other servers.

Related Topics