You are on page 1of 1

Filename:techskills-linuxshellscriptingbasics-6-2-2-userinput-options.

md
Show Name: Linux Shell Scripting Basics**
Topic Name: User Input
Episode Name: User Input: Options Pt.2
Description: In this episode, Daniel and Justin continue looking at
passing options to a shell script from the runline. Here they show you
how to employ getopt and getopts for expanding option functionality.
They also briefly discuss option standardization for better ease-of-use.
Keywords: [keyword1,keyword2,keyword3]

User Input: Options Pt.2


Using the getopt command
Group options together
command.sh -xyz
Format
getopt xyz
getopt x:yz
the colon tells getopt to expect a value
Getting your script to use getopt output
Use the set command
set -- $(getopt x:yz "$@")
This changes the way that the command-line options are being
interpreted.
set is telling the script to take $1 and TRANSLATE it through
getopt xyz or however it is stated
EXAMPLE: cli_options_getopt.sh -x +%Y%M%D -yz parm1 parm2 parm3
Maybe change this script in-show to be more simple, to use -xyz
Advancing to getopts
SINGULAR getopt doesn't recognize even with quotes
EXAMPLE: cli_options_getopt.sh -yz "test parm1" parm2 parm3
The first parameter should be "test parm1"
Never fear! getopts (PLURAL) is here!
Is a bit more powerful than getopt
It can handle
Sequentially iterates through the options using a while loop
Every time getopts runs it grabs the next option
The while loop does that well :)
Defines options much like getopt
x:yz
:x:yz Starting with a colon suppresses errors
Options are then placed into a variable
getopts :x:yz var1
Look at example
EXAMPLE: vim cli_options_getopts.sh
Employs 2 environmental variables
$OPTARG
Used if option Value is used
$OPTIND
Where getopts tracks the Parameters
Removes leading dashes
No need for dashes in the case function
-x) becomes x)
Any unknown option becomes a ?
Standardizing Options
You can make any options you like, BUT...
Standardizing the options you do use helps improve user experience
Let's look at some standard options
standard_options.txt

You might also like