Sample Header Ad - 728x90

Can you make a bash script's option arguments be optional?

2 votes
2 answers
7821 views
I would like either of these inputs to work. That is, the -n option itself is optional – I already know how to do that – but it then may have an optional parameter on top. If no parameter is given, a fallback value will be applied.
command -n 100
command -n
I can only make the former input type work or the latter, but not both.
HAS_NICE_THINGS=0
NICE_THINGS=50       # default value.

while getopts n: option; do
#while getopts n option; do    # NICE_THINGS would always be that default value.
#while getopts nn: option; do    # same.
	case "${option}" in
	n)
		HAS_NICE_THINGS=1
		if [[ ! -z "${OPTARG}" ]] && (( "${OPTARG}" > 0 )) && (( "${OPTARG}" <= 100 )); then
			NICE_THINGS=${OPTARG}
		fi;;
	esac
done

# error message:
# option requires an argument -- n
I'm not entirely sure yet if I would need a boolean for my script, but so far, just in case, I am logging one (HAS_NICE_THINGS). The end goal I had in mind was to set the JPG quality when eventually saving an image. Though, I can imagine this construct being useful elsewhere as well. I'm using Ubuntu 18.04.5 and GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu).
Asked by WoodrowShigeru (261 rep)
Aug 8, 2021, 01:09 PM
Last activity: Oct 3, 2024, 01:10 PM