optargs
Command line option processing in Bash can be done using various methods such as getopt and getopts.
Here, we explore different techniques along with examples to handle command line arguments efficiently.
Processing Options
Method 1: Using getopts with Short Options
Method 2: Using getopts with Long Options (GNU getopt)
optstring=":ab:c:"
longoptions="help,version"
# Parse options
getopt -o "$optstring" --long "$longoptions" -n 'script.sh' -- "$@" | while true; do
case "$1" in
-a)
# Option 'a' is present
;;
-b)
# Option 'b' is present with argument $2
shift
;;
-c)
# Option 'c' is present
;;
--help)
# Display help message
;;
--version)
# Display version information
;;
--)
shift
break
;;
*)
echo "Invalid option: $1"
break
;;
esac
shift
done
Method 3: Using getopts with Short and Long Options
Method 4: Using getopt with Short and Long Options (GNU getopt)
shortoptions="ab:c:"
longoptions="help,version"
# Parse options
parsed_options=$(getopt -o "$shortoptions" --long "$longoptions" -n 'script.sh' -- "$@")
eval set -- "$parsed_options"
while true; do
case "$1" in
-a)
# Option 'a' is present
;;
-b)
# Option 'b' is present with argument $2
shift
;;
-c
)
# Option 'c' is present
;;
--help)
# Display help message
;;
--version)
# Display version information
;;
--)
shift
break
;;
*)
echo "Invalid option: $1"
break
;;
esac
shift
done
Iterating over arguments
Example Script
#!/bin/bash
while getopts ":ab:c:help" option; do
case $option in
a)
echo "Option 'a' is present"
;;
b)
echo "Option 'b' is present with argument $OPTARG"
;;
c)
echo "Option 'c' is present"
;;
help)
echo "Displaying help message..."
;;
:)
echo "Missing argument for option -$OPTARG"
;;
?)
echo "Invalid option -$OPTARG"
;;
esac
done
shift $((OPTIND-1))
echo "Remaining arguments: $@"
- Run script