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.
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.
getopts to get
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 (
n is as an option-argument (
-n <name>). If
$name is not provided, then the
usage function is called.
$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:
pokemon function is called with the
$pokemon_name that was passed in.
The output is a
json file that contains pikachu’s information.
getopts to get
Building upon the last example, we can easily capture
A few things happened:
- I abstracted the
curlto its own function named
file_nameis parsed from the path. Ie.
i:was added to the
getoptsstring to allow the
getopts is useful for building plain / simple CLIs. If something more advanced is necessary,
bash is not the best language for the task.