How can I enhance my beginner Bash backup script?

0
3
Asked By CuriousCoder42 On

Hey everyone! 👋 I'm diving into Bash scripting and have written a simple backup script that creates a `.tar.gz` file of a specified directory, including the current date in the filename. Here's what I've got so far:

```bash
#!/bin/bash

echo "Welcome to the backup program"

BACKUP_FILE="backup_$(date +'%Y-%m-%d_%H-%M-%S').tar.gz"
TARGET_DIR="/mnt/f/Programming/Linux/"

if [ -d "$TARGET_DIR" ]; then
echo "Backing up..."
tar -cvpzf "$BACKUP_FILE" "$TARGET_DIR"
echo "Backup Done ✅"
else
echo "❌ Cannot create backup"
echo "Directory $TARGET_DIR does not exist"
exit 1
fi
```

It works fine, but I'd appreciate any suggestions on how to improve its robustness or efficiency, like better error handling, logging, user input options, or best practices for naming and organizing backups. Any thoughts? 🙏

3 Answers

Answered By ScriptSavant99 On

It's a good start! Just a tip: for private variables, consider using lower_case instead of CAPS_SNAKE. It helps clarify which variables are internal. Also, using `[[` instead of `[` in conditions can prevent some weird behavior due to how they're processed. And, you might want to check if the `tar` command was successful. Try this:

```bash
if tar ...; then
echo "Backup successful"
else
echo "Backup failed, check your space!"
fi
```
That'll give you peace of mind!

BackupBuddy88 -

Exactly what I was thinking!

Answered By LogMaster3000 On

You might want to consider adding input options for `BACKUP_FILE` and `TARGET_DIR`. It can be useful to specify a log file to track successes or errors, especially for automated runs. Implementing a logging system can help you debug easily. Also, exporting the logic as functions like `_check_inputs` and `_do_the_work` might make your script neater. Just some ideas!

Answered By RcloneFan22 On

I implemented something similar and set up a maximum number of backups. When I hit that limit, I automatically delete the oldest backups. I also use rclone to back up my files to a NAS. Plus, I run my script on startup if the last backup is older than two days. It keeps things tidy!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.