Skip to main content

Command Palette

Search for a command to run...

Creating a Bash Script to Compress a Directory into a Tar File

Published
2 min read

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

  1. Open Your Terminal: Start by opening your terminal. You will be writing the script in your preferred text editor (e.g., nano, vim).

  2. Create the Bash Script: Type the following command to create a new script file:

     nano backup_script.sh
    
  3. Write 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."
     fi
    
  4. Make the Script Executable: Save the file and exit the editor (for nano, press CTRL + X, then Y, then ENTER). Make the script executable by running:

     chmod +x backup_script.sh
    
  5. Run the Script: To run the script, use the following command, replacing /path/to/source with the directory you want to compress and /path/to/backup with your backup destination:

     ./backup_script.sh /path/to/source /path/to/backup
    
  6. Verify the Backup: After running the script, navigate to the backup directory to ensure that the .tar.gz file 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.


More from this blog

Amazon S3 Storage Classes

43 posts