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:

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!