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.
Basic Syntax
./script.sh [options] [arguments]
Processing Options
Method 1: Using getopts
with Short Options
while getopts ":ab:c" option; do
case $option in
a)
# Option 'a' is present
;;
b)
# Option 'b' is present with argument $OPTARG
;;
c)
# Option 'c' is present
;;
:)
# Missing argument for an option
;;
?)
# Invalid option
;;
esac
done
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
while getopts ":ab:c:help" option; do
case $option in
a)
# Option 'a' is present
;;
b)
# Option 'b' is present with argument $OPTARG
;;
c)
# Option 'c' is present
;;
help)
# Display help message
;;
:)
# Missing argument for an option
;;
?)
# Invalid option
;;
esac
done
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
# Accessing arguments
arg1=$1
arg2=$2
arg3=$3
# Iterating over arguments
for arg in "$@"; do
# Process each argument
done
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: $@"
./script.sh -a -b argument1 -c argument2 remaining_argument