Backing-up with scripts

Now that we have created some scripts, we may want to back these up to a different location. If we create a script to prompt us, we can choose the location and the type of files that we want to backup.

Consider the following script for your first practice. Create the script and name it $HOME/backup.sh:

#!/bin/bash
# Author: @theurbanpenguin
# Web: www.theurbapenguin.com
# Script to prompt to back up files and location
# The files will be search on from the user's home
# directory and can only be backed up to a directory
# within $HOME
# Last Edited: July 4 2015
read -p "Which file types do you want to backup " file_suffix
read -p "Which directory do you want to backup to " dir_name
# The next lines creates the directory if it does not exist
test -d $HOME/$dir_name || mkdir -m 700 $HOME/$dir_name
# The find command will copy files the match the
# search criteria ie .sh . The -path, -prune and -o
# options are to exclude the backdirectory from the
# backup.
find $HOME -path $HOME/$dir_name -prune -o \
-name "*$file_suffix" -exec cp {} $HOME/$dir_name/ \;
exit 0

You will see that the file is commented; though, in black and white, the readability is a little difficult. If you have an electronic copy of this book, you should see the colors in the following screenshot:

As the script runs, you may choose .sh for the files to backup and backup as the directory. The script execution is shown in the following screenshot, along with a listing of the directory:

Now you can see that we can start to create meaningful scripts with trivial scripting; although we strongly urge adding error checking of the user input if this script is for something other than personal use. As we progress into the book, we will cover this.