Shell script with getopt for short and long options -handling option with and without argument
1
vote
1
answer
116
views
Wanted to run a script
-- with option
./myscript.sh -a -g test
-- without option
./myscript.sh -a -g
The script looks like in below snippet, but don't see below script working correctly.
The getopt
for options specified with ::
(like g:: or gamma::) upon parsing g or gamma the passed argument is moved to end every time includes empty argument user option: --gamma '' -a -- 'test'
.
Refer the output of the script
$ sh optionwithandwithoutarg.sh --gamma test -a
user option: --gamma '' -a -- 'test'
arg info :- --gamma
arg info :- -a
arg info :- --
Alpha flag: true
Beta value: ''
Gamma value: 'default_gamma'
Remaining arguments: 'test'
## Script code used
#!/bin/bash
OPTIONS=$(getopt -o a,g::,b: --long alpha,gamma::,beta: --name "$0" -- "$@")
if [ $? -ne 0 ]; then
echo "Error: Invalid options provided."
exit 1
fi
echo "user option: $OPTIONS"
eval set -- "$OPTIONS"
# Initialize variables
ALPHA_FLAG="false"
BETA_VALUE=""
GAMMA_VALUE=""
while true; do
echo "arg info :- $1"
case "$1" in
-a | --alpha)
ALPHA_FLAG="true"
shift
;;
-b | --beta)
BETA_VALUE="$2"
shift 2
;;
-g | --gamma)
if [[ "$2" != "--" && -n "$2" ]]; then
GAMMA_VALUE="$2"
shift 2
else
GAMMA_VALUE="default_gamma" # Assign a default if no argument given
shift 2
fi
;;
--)
shift
break
;;
*)
echo "Not supported option"
exit 1
;;
esac
done
echo "Alpha flag: $ALPHA_FLAG"
echo "Beta value: '$BETA_VALUE'"
echo "Gamma value: '$GAMMA_VALUE'"
echo "Remaining arguments: '$*'"
How to handle the options with and without argument with getopt
Asked by Tim
(113 rep)
Aug 2, 2025, 02:26 PM
Last activity: Aug 4, 2025, 10:38 AM
Last activity: Aug 4, 2025, 10:38 AM