Creating a Bash Script to Compress a Directory into a Tar File
In this blog post, we will walk through the steps to create a Bash script that compresses a specified directory into a .tar file, includes the current date and time in the filename, and then moves it to a designated backup folder. This script is a practical way to ensure your files are safely backed up and organized.
Prerequisites
Before you start, ensure you have the following:
A Unix-based system (Linux or macOS).
Basic knowledge of using the terminal.
Sufficient permissions to read the target directory and write to the backup location.
Step-by-Step Guide
Open Your Terminal: Start by opening your terminal. You will be writing the script in your preferred text editor (e.g., nano, vim).
Create the Bash Script: Type the following command to create a new script file:
nano backup_script.shWrite the Script: Copy and paste the following script into your editor. This script will compress a specified directory and move it to the backup folder.
#!/bin/bash # Variables SOURCE_DIR="$1" # Directory to compress, passed as the first argument BACKUP_DIR="$2" # Backup directory, passed as the second argument # Get the current date and time TIMESTAMP=$(date +"%Y%m%d_%H%M%S") # Create a tar.gz file tar -czf "${BACKUP_DIR}/backup_${TIMESTAMP}.tar.gz" -C "$SOURCE_DIR" . # Check if the command was successful if [ $? -eq 0 ]; then echo "Backup of '$SOURCE_DIR' completed successfully and moved to '$BACKUP_DIR'." else echo "Backup failed." fiMake the Script Executable: Save the file and exit the editor (for nano, press
CTRL + X, thenY, thenENTER). Make the script executable by running:chmod +x backup_script.shRun the Script: To run the script, use the following command, replacing
/path/to/sourcewith the directory you want to compress and/path/to/backupwith your backup destination:./backup_script.sh /path/to/source /path/to/backupVerify the Backup: After running the script, navigate to the backup directory to ensure that the
.tar.gzfile has been created with the current timestamp in its name.
Conclusion
This Bash script is a simple yet effective way to automate the backup process for directories in Unix-based systems. By incorporating the current date and time, you can easily manage multiple backups without overwriting previous files.
Feel free to modify the script to suit your needs, such as adding error handling or logging features. Happy scripting!
For further reading and more Bash scripting tips, you can check out resources like LinuxCommand.org and GNU Bash Manual.