A template for args parsing in shell scripts

Home   »   A template for args parsing in shell scripts

#!/usr/bin/env bash

# A template for args parsing in shell scripts

usage()
{
    echo "Usage: argument_parse.sh [-h] [-a] -b VALUE"
    echo ""
    echo "Description of what the script does."
    echo ""
    echo "Optional arguments:"
    echo "    -h, --help            Show this help message and exit."
    echo "    -a, --a-longer        Sets some useful flag (single argument)."
    echo ""
    echo "Required arguments:"
    echo "    -b, --b-longer        Set some useful value (argument with value)."
    echo ""
}

A_FLAG_SET=0
B_VALUE="NULL"

while (( "$#" )); do
    case "$1" in
        -h|--help)
            usage
            exit
            ;;
        -a|--a-longer)
            A_FLAG_SET=1
            shift
            ;;
        -b|--b-longer)
            if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
                B_VALUE=$2
                shift 2
            else
                echo "Error: Argument for $1 is missing" >&2
                exit 1
            fi
            ;;
        -*|--*=) # unsupported flags
            echo "Error: Unsupported flag $1" >&2
            exit 1
            ;;
        *) # preserve positional arguments
            echo "Positional: $1"
            shift
            ;;
    esac
done


if [[ $B_VALUE == "NULL" ]]; then
    usage
    exit 1
else
    echo "B_VALUE have been set to '$B_VALUE'"
fi

if [[ $A_FLAG_SET == 1 ]]; then
    echo "A_FLAG is active! "
else
    echo "A_FLAG is not active!"
fi

Leave a Reply

Your email address will not be published. Required fields are marked *