I want to have getopts setup for my script in such a way that it accepts no argument (-p
) but so that it can also accept an argument (-p library
). Both need to be accepted. They're (argument and no argument) are both allowed. The argument should be allowed to be any string. See below:
while getopts "p:sdih" opt; do
case ${opt} in
p )
#WHEN NO ARGUMENT IS GIVEN, DO THIS
selection="plex"
#WHEN AN ARGUMENT IS GIVEN, DO THIS
selection="plex"
argument=true
optarg="$OPTARG"
;;
s )
selection="sonarr"
;;
d )
selection="deluge"
;;
i )
selection="info"
;;
h )
usage | column -t -s "|"
exit
;;
\? )
echo "Invalid option"
usage | column -t -s "|"
exit
;;
esac
done 2>/dev/null
shift $((OPTIND -1))
That's how it needs to work. But I'm new to getopts so I don't know how to do this yet...
To check for missing arguments, start optstring with a colon
:
by changing"p:sdih"
to":p:sdih"
Then, add a case argument before
\?)
like so:You can check for more than one option by evaluating
"$OPTARG"
More information can be found here