Bash Script Skeleton

Last modified: 
Thursday, May 12th, 2016
Topics: 
Bash

A skeleton file for a basic bash script.

#!/usr/bin/env bash

#
# A basic bash script stub.
#
usage() {
    echo "output usage instructions here"
    echo
}

version() {
    echo "output version info here."
    echo
}

main() {
    if [ "$#" -lt 1 ]; then
        usage; exit 1
    fi

    local subcommand="$1"; shift

    case $subcommand in
        "-h"|"--help")
            usage; exit 0
            ;;
        "-v"|"--version")
            version; exit 0
            ;;
    esac


    # Here are two different ways to get the script directory.
    local workingdir="$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")"
    echo $workingdir

    local startdir="${BASH_SOURCE%/*}"
    if [[ ! -d "$startdir" ]]; then "$startdir=$(pwd)"; fi
    echo $startdir

    # And this will get you the fullpath to a script, MOST of the time
    # See https://sittinginoblivion.com/wiki/get-path-currently-executing-bash-script
    local fullpath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    echo $fullpath

    exit 0
}

main "$@"


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.