A Unix/Linux shell script to make a quick backup of a directory

As a brief note today, I just created this little Unix/Linux shell script that I named tarquick, and it lets me quickly create a tar/gz backup of one directory. It does a lot of the tar work for you, and all you have to do is specify an optional directory name:

#!/bin/sh

# NAME:    tarquick
# VERSION: 0.2
# this is a little shell script that makes a tar/gzip
# backup of one directory — 'src', by default. i 
# created it to make it easier to rapidly create a 
# backup of my work.

# license: GNU GPLv3
# see:     https://www.gnu.org/licenses/gpl-3.0.en.html

# -----------------------------------------------------------
# assign 'dir' to "src", but if a different name is
# provided, use it instead.
# -----------------------------------------------------------
dir="src"
if [ $1 ]
then
    dir="$1"
fi

# -----------------------------------------------------------
# bail out if the directory does not exist.
# -----------------------------------------------------------
if [ ! -d $dir ]
then
    echo "The directory '$dir' does not exist."
    echo "Quitting without making a backup."
    exit
fi

# -----------------------------------------------------------
# create a backup filename with the date, time, and dir name.
# write the backup to my other hard drive, which is mounted
# at ~/ExternalDrive.
# note that the filename is unique to the second of the day.
# -----------------------------------------------------------
d=`date +"%Y.%m.%d"`            # date format
t=`date +"%H.%M.%S"`            # time format
filename=${dir}-${d}-${t}.tgz
canonFilename=~/ExternalDrive/Backups/$filename

echo "Creating $canonFilename ..."

# -----------------------------------------------------------
# make the tar file
# -----------------------------------------------------------
tar czvf $canonFilename $dir

I have currently named this script tarquick, because it quickly makes a tar backup. Mostly I want a name that begins with "tar" so I can type "tar" at the command line, then press the Tab key to easily find my script name.

Another important thing about this script is that the filename it creates is unique to the second of the day, so you don’t have to type much, and don’t have to worry about filenames; you just make a quick backup.

Using the script looks like this:

$ tarquick foo
Creating /Users/al/ExternalDrive/Backups/foo-2021.10.27-11.47.23.tgz ...

If you ever wanted a shell script to make a quick backup of a directory, I hope this is helpful.