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:

Have Questions? Post them here!
- How to Assign Bash Command to Variable
- How to Kill a port using bash terminal command?
- Bash For Loop Example
- bash: netstat: command not found
- Bash getopts Command Example
- How to fix bash ping command not found error
- [Fix] bash: script.sh: /bin/bash^M: bad interpreter: No such file or directory
- [fix] bash: ssh: command not found
- Fix bash: script.sh: Permission denied Error
- bash: ls command to see list files in current directory all subdirectories
- How to see Created Accessed Modified and Changed dates of a file using bash terminal command
- How to use Autocomplete and Autosuggestion in Shell Commands
- Bash Hello World! Script Tutorial
- Install Bash Completion on macOS
- bash get year 2021 calendar
- How to create new user account in Windows bash
- Bash command to wait for seconds
- Know Bash shell version command
- How to start or open a new bourne-again shell (bash) session on Windows using Command Line CMD
- How to check your IP using bash for Windows?
- Bash Script to prefix files with sequential numbers in a directory
- How to Compare Strings in Bash
- Command to Sort File In Reverse Order [Unix/Linux/macOS]
- How to know the current shell you are logged in?
- List all Username and User ID using Bash Command
- Fix: error: could not lock config file /etc/gitconfig: Permission denied - Git
- Change the background of Tkinter label or text - Python
- New-SPLogFile PowerShell - create new SharePoint log file - SharePoint
- Add imports in eclipse shortcut key combinations - Eclipse
- Type R is already defined error : Android Error - Android
- zsh: command not found [fix] macOS - zsh
- Save Screenshots on Mac in JPG instead of PNG Format - MacOS
- Notepad++ select all above or below lines - NotepadPlusPlus