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 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
READ  Remove all mistyped emails, unsubscribed emails or bounced emails from Email List

Leave a Reply

Your email address will not be published. Required fields are marked *