Skip to content
Advertisement

Linux Shell Script – Mounting and Backing Up Files

I’m writing my first shell script. I want to check if a filesystem is mounted. If so, then backup the documents from my main drive to the backup that is mounted. If not, mount the filesystem, then backup the documents.

#!/bin/bash
# Check if linux_backup filesystem is mounted
# Mount filesystem if not mounted already, and then backup documents

docs= "/home/user1/Documents"
mount= "/run/media/user1"
docsbackup= "/run/media/user1/linux_backup/home/user1/Documents"
filesystem= "/dev/sdc3"

sync_files() {
    SOURCE=$1
    TARGET=$2
    sudo rsync --progress -r --update -aAXv $SOURCE $TARGET
}

if mount | awk '{if ($3 == "/run/media/user1") { exit 0}} ENDFILE{exit -1}';
then
    echo "linux_backup is mounted"
    sync_files $docs $docksbackup
else
    echo "linux_backup is not mounted. Will mount now"
    mount $filesystem $mount
    sync_files $docs $docksbackup
fi

I executed the script, yet all I got was a lot of text. It didn’t perform as I wanted. Did I not use the right options or arguments for one of the functions?

Advertisement

Answer

I suggest such a script for you:

docs="/home/user1/Documents"
mount="/run/media/user1"
backup="/run/media/user1/linux_backup/home/user1/Documents"
device="/dev/sdc3"

sync_files() {
    SOURCE=$1
    TARGET=$2
    sudo rsync --progress -r --update -aAXv $SOURCE $TARGET
}

# Check if FS is mounted
if grep -qs "/run/media/user1" /proc/mounts; then
    # Device is mounted
    sync_files $docs $docksbackup
else
    # Device isn't mounted, mounting...
    mount $mount $device
    # Back upping
    sync_files $docs $docksbackup
fi
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement