getopts command in linux shell script

The getopts command in shell script is used to check the valid command line arguments passed into script. The syntax of using getopts inside shell script is,

getopts {optsring} {variable_name}

From the manual page,
"optstring contains the option letters to be recognized; if a letter is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. Each time it is invoked, getopts places the next option in the shell variable variable_name, When an option requires an argument, getopts places that argument into the variable OPTARG. On errors getopts diagnostic messages are printed when illegal options or missing option arguments are encountered. If an illegal option is seen, getopts places ? into variable_name."

For example you have a shell script named student_info that would be run by,
./student_info -i 024434 -a 23 -d CIT -s male
where student_info is the shell script name
-i is used for the student id.
-a is used for age.
-d is used for department.
-s is used for sex.

Now if you see user is giving wrong argument rather than these, then you can show user about the script usage information.

Let's look at the code.

# vi getopts.sh
{
echo "Usage Syntax: $0 -i -a -d -s"
echo "-i Student ID"
echo "-a Age"
echo "-d Department"
echo "-s Sex"
exit 1
}
if [ $# -lt 1 ]
then
help_menu
fi
while getopts i:a:d:s: option
do
case "$option" in
i) id="$OPTARG";;
a) age="$OPTARG";;
s) sex="$OPTARG";;
d) dept="$OPTARG";;
\?) help_menu
esac
done
echo "Student ID: $id ,Age: $age ,Sex: $sex ,Department: $dept "

# chmod +x getopts.sh

If you run getopts.sh without any argument then it will display the usage syntax.
# ./getopts.sh
Usage Syntax: ./getopts.sh -i -a -d -s
-i Student ID
-a Age
-d Department
-s Sex

If you give correct arguments then it will display as below.
# ./getopts.sh -i 024434 -a 23 -s male -d CIT
Student ID: 024434 ,Age: 23 ,Sex: male ,Department: CIT

Comments

Popular posts from this blog

ORA-04062: timestamp of procedure has been changed

ORA-00939: too many arguments -when case arguments exceed 255

ORA-31655: no data or metadata objects selected for job