# Real-Time Shell Scripting – Part 1-Automate Log File Backups Using Shell Script + Cron + GitHub

This is the first script in my “10 Real-Time Shell Scripts” collection — where I document useful shell automation tasks with code, explanations, and troubleshooting. In this post, I’ll cover:

✅ Writing a shell script to back up log files   
✅ Automating it using `cron`   
✅ Pushing the script to GitHub from a Linux VM   
✅ Fixing real issues I faced

---

### 1\. The Backup Script (Full Code)

Here’s the complete script that backs up `/var/log` files into a timestamped.`tar.gz` archive:

`#!/bin/bash`

`# Source directory to back up`

`source_dir="/var/log"`

`# Destination directory`

`backup_dir="/home/ubuntu/log_backups"`

`# Backup filename with timestamp`

`backup_filename="Log_Backup_$(date +'%Y-%m-%d_%H-%M-%S').tar.gz"`

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

`# Compress and archive the logs`

`tar -czvf "$backup_dir/$backup_filename" "$source_dir"`

`# Check if backup was successful`

`if [ $? -eq 0 ]; then`

`echo "Backup successful: $backup_filename"`

`else`

`echo "Backup failed" fi`

### OUTPUT:

Make sure you give execute permission before you run the code:

`sudo chmod +x backup.sh`→ giving execute permissions

`./backup.sh`→ running the script

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205319225/0aca6b47-252e-4a57-99c3-f211648af6d4.jpeg align="center")

### Line-by-Line Explanation:

#### `#!/bin/bash`

* **Shebang line**.
    
* Tells the system to execute this script using the **Bash shell** located at `/bin/bash`.
    

---

#### `source_dir="/var/log"`

* Creates a variable named `source_dir`.
    
* It stores the **path of the directory** you want to back up.
    
* `/var/log` is typically where system logs are stored in Linux.
    

---

#### `backup_dir="/home/ubuntu/log_backups"`

* Defines where you want to save the backup file.
    
* This is the **destination directory** on your system.
    
* `mkdir -p` later ensures this directory exists (or is created).
    

---

#### `backup_filename="Log_Backup_$(date +'%Y-%m-%d_%H-%M-%S').tar.gz"`

* Creates a **dynamic filename** for your backup.
    
* `$(date +'%Y-%m-%d_%H-%M-%S')` generates a current timestamp.
    
* Full result: a name like `Log_Backup_2025-06-22_21-30-00.tar.gz`
    
* The `.tar.gz` extension means it will be a **compressed archive**.
    

---

#### `mkdir -p "$backup_dir"`

* Makes sure the destination directory exists.
    
* `-p` ensures no error if it already exists and creates **any missing parent directories**.
    

---

#### `tar -czvf "$backup_dir/$backup_filename" "$source_dir"`

* This is the **main backup command**.
    
* `tar` is used to archive files.
    
* Flags:
    
    * `-c`: create a new archive
        
    * `-z`: compress using gzip
        
    * `-v`: verbose (shows progress)
        
    * `-f`: file name to write to (output archive)
        
* It compresses the source directory into the filename path created above.
    

---

#### `if [ $? -eq 0 ]; then`

* `$?` stores the **exit status** of the last executed command.
    
* If `tar` was successful, it will be `0`.
    
* This line starts a conditional check: *Did the backup succeed?*
    

---

#### `echo "Backup successful: $backup_filename"`

* This prints a success message with the actual backup filename.
    

---

#### `else`

* If `$?` is **not 0**, the backup failed.
    

---

#### `echo "Backup failed"`

* This message will print if the backup didn’t complete successfully.
    

---

#### `fi`

* Closes the `if` block.
    
    ---
    

## 3\. 🕒 Automate Your Backup Using `cron`

You can schedule your backup script to run automatically every day at 2 AM using a cron job.

Steps:

1\. Open crontab:

`crontab -e` Then enter 1 to open nano editor.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205431939/726bb298-9131-4d09-862a-1360a4972a53.jpeg align="center")

2\. Add this line at the bottom:

0 2 \* \* \* /home/ubuntu/backup-script/[backup.sh](http://backup.sh) &gt;&gt; /home/ubuntu/backup-cron.log 2&gt;&1

---

## 4\. 🐧 Push Your Backup Script to GitHub from Linux VM

If you’re using a fresh Linux VM, first make sure Git is installed:

Install Git:

`sudo apt update sudo apt install git -y`

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205535761/8701f7b5-94ec-4818-8f80-c0716449a8dd.jpeg align="center")

Clone Your GitHub Repository:

`git clone` [`https://github.com/JU2512/10-Real_Time-Shell-Scripts.git`  
`cd`](https://github.com/JU2512/10-Real_Time-Shell-Scripts.git%EF%BF%BCcd) `10-Real_Time-Shell-Scripts`  
`mkdir backup-script cd backup-script vi` [`backup.sh`](http://backup.sh)

Push Changes to GitHub:

> ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205612815/0478a9e4-c55e-426d-bb26-3ad597f6ef63.jpeg align="center")

`cd ~/10-Real_Time-Shell-Scripts git add . git commit -m "Add log file backup script" git push origin main`

---

## 5\. 🛠️ Troubleshooting: Real Errors I Faced & How I Solved Them

### ❌ 1. "Bad Interpreter: No such file or directory"

Problem:  
Got error `/bin/bash^M: bad interpreter: No such file or directory` when running `./`[`backup.sh`](http://backup.sh)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205861669/0dba770c-d49f-4c3c-bc96-b4936b7d1d9d.jpeg align="center")

Solution:  
I deleted the original file and rewrote it inside the VM using `vi`, which ensured proper Unix line endings.

### ❌ 2. "Permission Denied" When accessing `/var/log`

Problem:  
Script failed with permission error while accessing `/var/log`

Solution:  
Used `sudo ./`[`backup.sh`](http://backup.sh) to run the script with elevated permissions.

### ❌ 3. Unable to Push Code to GitHub

Problem:  
Git push failed due to authentication error

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751205904523/010fd75f-a81f-4b36-ab11-30232e062f40.jpeg align="center")

Solution:  
\- Generated a new personal access token (PAT) from GitHub with `repo` access  
\- Used the token when prompted for password during `git push`

---

## 🔜 More Scripts Coming up- Stay tuned

Thanks for reading — I hope these examples help you in real-world DevOps work!

***You can get access to more such scripts in my GitHub repo. 🚀***

link → [10\_Real-Time-Scripts](https://github.com/JU2512/10-Real_Time-Shell-Scripts)

**Happy Learning:}**

👩‍💻 Jyothi Urade | #FromCloudToOps
