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
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap