Thursday, January 23, 2014

Use of getopt command in linux

It is observerd that there are many students and many people who create their own commands, it is more obvious that they create their commands according to the user satisfaction and theri ease. So many commands use the getopt command to create their own commands with particular options. 
 It may be possible that a command does multiple operations using different options of the command, for example: $ps -a command where -a defines Select all processes except both session leaders (see getsid(2)) and processes not associated with a terminal.

In similar way one can create options for his command in shell script using the getopts command. A sample program is shown below:
#!/bin/bash



getopts ab choice

case $choice in

a) echo “You selected option A.”

;;

b) echo “You selected option B.”

;;

?) echo “You selected Wrong Choice.”

;;

esac



Now run this program using the command

$sample.sh -a

The output of the above command will be seen as follows:

Figure 1: Run sample Example



In the above problem ab are the options that are passed as parameters to the command. getopts accepts single character options from the command line provided the option is preceded by a minus(-) sign.



To make your own command you can follow the following blog:




No comments:

Post a Comment