Bash getopts Command Example


If you want to build a console-based bash script that has command-line options build-in, you can make use of the getopts Unix command.

Example:

#!/bin/bash

while getopts ":a:b:" opt; do
  case $opt in
    a)
      num1="$OPTARG"
      ;;
    b)
      num2="$OPTARG"
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

if [ -z "$num1" ] || [ -z "$num2" ]; then
  echo "Usage: $0 -a num1 -b num2" >&2
  exit 1
fi

sum=$(expr $num1 + $num2)
echo "The sum of $num1 and $num2 is $sum."
Output:

./addition.sh -a 10 -b 20

The sum of 10 and 20 is 30.

Bash getopts Example
-




Have Questions? Post them here!