Skip to main content

Parsing command-line arguments in a bash script

·162 words·1 min
Code Bash
Table of Contents

Options separated by spaces
#

This is the more flexible approach, where the option can easily be followed by an arbitrary number of items to take in and be shifted pass by.

#!/usr/bin/env bash

while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
        -e|--extension)
        EXTENSION="$2"
        shift # past argument
        shift # past value
        ;;
        --default)
        DEFAULT=YES
        shift # past argument
        ;;
        *)    # unknown option
        shift # past argument
        ;;
    esac
done

echo FILE EXTENSION  = "${EXTENSION}"

Options separated by ‘=’
#

This is to say, command line options can be done like so -l=blah --lib=blah.

This is a bit less flexible, as each item would have to be paired with the explicit optin tag. But some do still prefer it.

#!/usr/bin/env bash

for i in "$@"
do
    case $i in
        -e=*|--extension=*)
        EXTENSION="${i#*=}"
        shift # past argument=value
        ;;
        --default)
        DEFAULT=YES
        shift # past argument with no value
        ;;
        *)
            # unknown option
        ;;
    esac
done

echo "FILE EXTENSION  = ${EXTENSION}"