Home » Scripting and Automation » Bash / Shell Scripts » How to use getopts to Accept Variable Arguments for Bash Script ?

How to use getopts to Accept Variable Arguments for Bash Script ?

getopts is a built-in Unix shell command for parsing command-line arguments. It is designed to process command line arguments, based on the C interface of getopt.

We have written a simple example script in this post, to demonstrate this.

  • bash scriptname.sh -h => it will display the help
  • bash scriptname.sh -c =>  script displays “Good Morning / Good after noon/ Good Evening / Good NIght” if the time is ” 00-12 / 12-16 / 16-20 / Remaining”
  • bash scriptname.sh -e => it should recursively ( from current path ) search and delete the file “filename” from the located path.
#!/usr/bin/env bash

FILE_TO_DELETE="test.txt"

time_hrs=$(date +"%H")
time_min=$(date +"%M")

print_help () {
	printf "\nHELP => "
	printf "\n        This is help\n"
}

message () {
	hrs=`expr $time_hrs + 0`
	min=`expr $time_min + 0`
	datetime="$hrs:$min"
	printf "time is $datetime\n"

	if [ $hrs -lt 16 ]
	then
	    	printf "Good Morning.\n"
		return
	fi

	if [ $hrs -gt 16 ]
	then
		if [ $hrs -lt 18 ]
		then
			printf "Good Afternoon\n"
		else
   	 		printf "Good Evening\n"
		fi
	fi
}

search_delete_filename () {
	printf "search and delete files\n"
	find . -type f -name $FILE_TO_DELETE -exec rm -f {} \;
}

invalid_args () {
	printf "invalid argument while starting script\n"
}

while getopts 'ech' OPTION
do
	case $OPTION in
	e) search_delete_filename	;;
	c) message	;;
	h) print_help		;;
	*) invalid_args	;;
	esac
done
	shift $(($OPTIND - 1))

Run the above script with individual arguments as,

 $ bash scriptname.sh -h

HELP => 
        This is help
$ bash scriptname.sh -c
time is 23:32
Good Evening
$ bash scriptname.sh -e
search and delete files

You can also invoke all arguments as,

$ bash scriptname.sh -hec

HELP => 
        This is help
search and delete files
time is 23:35
Good Evening

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment