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

Post Free Ads for Agri, Solar, Eco products

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 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

Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply