Building a simple CLI in Bash may seem like a herculean task; however, getopts
provides an easy-to-use interface out of the box! For this tutorial, we’ll be using the https://pokeapi.co/ to build a simple CLI for fetching resources from the Pokemon world.
What is getopts
?
Given from the documentation,
The getopts utility shall retrieve options and option-arguments from a list of parameters. It shall support the Utility Syntax Guidelines 3 to 10, inclusive, described in XBD Utility Syntax Guidelines.
getopts
is a command that makes defining options and option-arguments seamless using a list of parameters.
Use getopts
to get pokemon
Let’s start by making the boilerplate:
|
|
As seen above, getopts
accepts a parameter list – ie. hn:
. Colons (:
) are used to denote that an argument requires a value. In this case, h
is as an option (-h
) while n
is as an option-argument (-n <name>
). If $name
is not provided, then the usage
function is called.
Within the case
statement, $OPTARG
contains the option-argument value that is passed from the user. For good measure, it is piped through tr
to lowercase it (click here for more information about casing strings in Bash).
Now, let’s add a simple curl command that calls the /pokemon
api given the name:
|
|
The pokemon
function is called with the $pokemon_name
that was passed in.
|
|
The output is a json
file that contains pikachu’s information.
Use getopts
to get items
Building upon the last example, we can easily capture items
:
|
|
A few things happened:
- I abstracted the
curl
to its own function namedrequest
- The
file_name
is parsed from the path. Ie./items/master-ball
->master-ball.json
- The
pokemon
anditem
both callrequest
i:
was added to thegetopts
string to allow the-i <item>
option-argument.
What’s next?
getopts
is useful for building plain / simple CLIs. If something more advanced is necessary, bash
is not the best language for the task.