How to use getopts to accept variable arguments for bash script / passing command line arguments to shell script

getopts allows you to accept command line arguments for the bash script, below is demo script which does following this,

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


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`
	printf "time is $datetime\n"

	if [ $hrs -lt 16 ]
	    	printf "Good Morning.\n"
	if [ $hrs -gt 16 ]
		if [ $hrs -lt 18 ]
			printf "Good Afternoon\n"
   	 		printf "Good Evening\n"

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
	case $OPTION in
	e) search_delete_filename	;;
	c) message	;;
	h) print_help		;;
	*) invalid_args	;;
	shift $(($OPTIND - 1))

Run the above script with individual arguments as,

 $ bash -h

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

You can also invoke all arguments as,

$ bash -hec

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

Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense Multimedia - Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question