Back to course

80. Writing Your First Simple Shell Script (Backup Example)

Linux Basics: From Zero to CLI Hero

Final Project: A Simple Backup Script

Let's combine several commands learned throughout the course (echo, date, mkdir, tar) into a useful script.

Script Goal

Create a timestamped compressed backup of the ~/Documents folder and store it in a ~/Backups directory.

The Script (daily_backup.sh)

  1. Create the file and add the shebang: bash $ touch daily_backup.sh $ nano daily_backup.sh # Or use your preferred editor

  2. Add the content: bash #!/bin/bash

1. Define variables

BACKUP_DIR=/Backups DATE_STAMP=$(date +%Y-%m-%d_%H%M%S) ARCHIVE_NAME="documents_backup_"${DATE_STAMP}".tar.gz" SOURCE_DIR=/Documents

2. Ensure the backup directory exists

mkdir -p $BACKUP_DIR

3. Create the compressed archive

echo "Starting backup of $SOURCE_DIR..."

tar -czvf $BACKUP_DIR/$ARCHIVE_NAME $SOURCE_DIR

4. Final confirmation

if [ $? -eq 0 ]; then echo "Backup successful: $ARCHIVE_NAME" else echo "Backup FAILED!" fi

  1. Make executable and run: bash $ chmod u+x daily_backup.sh $ ./daily_backup.sh

    Check the result

    $ ls -lh Backups/

Congratulations! You have completed the foundation of Linux administration and command line mastery.