Bash: Command Line Arguments

Handy options for handling command line arguments within your shell scripts. These aren’t necessarily the best, but they’ll get you started.

Option 1: Using Case

#!/bin/bash

while getopts c:i:r: flag
do
    case "${flag}" in
        c) cloud=${OPTARG};;
        i) instance=${OPTARG};;
        r) region=${OPTARG};;
    esac
done
echo "Cloud: $cloud";
echo "Instance: $instance";
echo "Region: $region";

Option 2: Simplistic

#!/bin/bash

if [ "$#" -lt 3 ]; then
    echo "Illegal number of parameters:"
    echo -e "<cloud> <instance> <region>"
    echo -e "cloud:   ie, gcp | aws | azure"
    echo -e "instance: ie, the-instance"
    echo -e "region:    ie, us-central1-a"
    exit 1
fi

cloud=$1
instance=$2
region=$3
Scroll to Top