Linux script for system backup

Linux script for system backup

Creating a backup script involves a few steps and can vary depending on your requirements, such as what to save and where to store the backups. Here's a simple example of a backup script that creates a compressed archive of selected directories and places them in a backup folder.

Keep in mind that this script is just a simple example. You should adjust it for your own needs, like choosing which directories to back up and where to save the backups. You could also think about using a tool like cron to automatically run the script for scheduled backups.


# Define backup directories and locations
source_dirs=("/path/to/source1" "/path/to/source2")

# Create a timestamp for the backup
timestamp=$(date +"%Y%m%d%H%M%S")

# Create the backup directory if it doesn't exist
mkdir -p "$backup_dir"

# Create a compressed tarball containing the specified directories
tar -czvf "$backup_dir/$backup_file" "${source_dirs[@]}"

# Check if the backup was successful
if [ $? -eq 0 ]; then
  echo "Backup completed successfully. Backup stored in: $backup_dir/$backup_file"
  echo "Backup failed."

Here's a breakdown of how this script works:

  1. Set the backup_dir variable to specify the folder where backups will be stored.

  2. Define the source_dirs array to list the directories you want to back up.

  3. Create a timestamp to include in the backup file's name. This ensures that each backup has a unique name.

  4. Create the backup directory if it doesn't exist.

  5. Use tar to create a compressed archive (tarball) of the specified directories. The -czvf options stand for "create," "compress," "verbose," and "file."

  6. Check the exit status of the tar command. If it's successful (exit code 0), print a success message. Otherwise, print an error message.

Don't forget to change this script by using your real directory paths instead of /path/to/backup/folder and /path/to/sourceX. You can also improve this script by adding features like automatically deleting old backups or sending backups to other places.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!