Bash getops Example

Bash getops Example

Tags :

Category : How-to

Get Social!

getopts is a way of adding intuitive options to custom bash scripts in Linux. getopts is a command that’s built into all recent versions of Bash, and is a more recent version of getopt (notice there is no ‘s’).

You’re not able to do anything too fancy with getopts, such as GNU long options like –filter, but you are able to easily pass in semi-meaningful arguments with relative ease.

Let’s take a look at the below example to understand what we’re getting into. 

Calling getopts Scripts

So that we know what we’re getting into, lets start with calling a script that accepts 3 arguments.

  • A port
  • A Hostname
  • A force parameter

The script we’re creating is just an example usage for getopts so each of the above parameters won’t really do anything, so I’ll leave your imagination to come up with a reason for wanting to collect such information. That said, we’re going to call our example script send_curl_command.sh and it will expect the above mentioned parameters to be passed in to work. 

send_curl_command.sh -p 443 -h api.jamescoyle.net -f

getopts Example

#!/bin/bash

# Echo usage if something isn't right.
usage() { 
    echo "Usage: $0 [-p <80|443>] [-h <string>] [-f]" 1>&2; exit 1; 
}

while getopts ":p:h:f" o; do
    case "${o}" in
        p)
            PORT=${OPTARG}
            [[ $PORT != "80" && $PORT != "443" ]] && usage
            ;;
        h)
            HOST=${OPTARG}
            ;;
        f)  
            FORCE=1
            ;;
        :)  
            echo "ERROR: Option -$OPTARG requires an argument"
            usage
            ;;
        \?)
            echo "ERROR: Invalid option -$OPTARG"
            usage
            ;;
    esac
done
shift $((OPTIND-1))

# Check required switches exist
if [ -z "${PORT}" ] || [ -z "${HOST}" ]; then
    usage
fi

echo "p = ${PORT}"
echo "h = ${HOST}"

The above snippet shows a relatively simple example of how to use getopts and can be broken into 3 main parts.

usage is a bash function that echos the script name, and some literal text on which parameters are accepted and then exits the script. The idea here is to call this function if anything is wrong with the arguments passed, so that a helpful hint can be given to the user and the script can exit.

The if block at the bottom of the script runs a few checks on the switches to ensure that they exist. The -z attribute is a simple bash test to ensure that the variable is set – it doesn’t do anything more clever than that. In addition, in the middle block you’ll find another check  [[ $PORT != “80” && $PORT != “443” ]] which checks that the p variable is set and is equal to either 80 or 443. You can check in either location, or both, just remember to call usage if something isn’t right so that the script can exit.

That means only the central block of code remains – and this is the meat of the getopts command. Much of this block can be considered boilerplate code, however there are 2 parts you’ll need to edit: the first line of the code between the quotation marks, which are the parameters that instruct getopts how to work, and the case statement. 

getopts Arguments and case Statement

The quoted arguments following the getopts command can look fairly cryptic at first, but once it’s broken down into its individual parts it’s really easy to build up the functionality you need. Keeping with the above example, let’s take a look at the getopts arguments “:p:h:f” o.

  • “:” (colon) is there to denote if getopts should throw an error if parameters are missing, which are specified as required (more on that in the last bullet point below). If you omit the : then getopts would throw generic errors – something that we’ll handle manually for this example to provide a more meaningful output in the context of our script.
  • “p:” is the first parameter that we tell getopts to expect. p specifies the character that will be passed on the command line when calling the script – for example myscript.sh -p. The colon specifies that an attribute must follow the switch, for example myscript.sh -p 443. During processing, the value 443 will be parsed with the -p switch.
  • “h:” is exactly the same as the above -p switch, only the character here is p.
  • “f” is, as above, specifying that the -p switch is expected however here there is no colon :. That’s because the -f switch will not have an attribute payload following it, for example 
    myscript.sh -p 443 -h myhost.com -f
  • “o” outside of the parenthesis is a lonely o. This value will be filled with either:
    • The switch being received, if it’s a valid switch such as ph or f.
    • a ? if the switch being passed is not an accepted switch (not specified in the getopts configuration). This is only available if the getopts argument begins with : as per the first bullet point above.
    • : if the switch is acceptable but doesn’t contain an argument when it should (configured with a : such as “p:”). This is only available if the getopts argument begins with : as per the first bullet point above.

That’s all the configuration needed for the getopts command to function however, to make useful we need to understand the arguments that are passed in, check them to ensure they’re sensible and make them available for the script to use.

case Statement

The case statement is called multiple times for each argument of getopts. In the above example, the first case check is for p which would be called when the -p argument is passed with variables. The code will then check that p is either 80 or 443 and set the variable PORT to equal the value passed in. case items h and f should be easy enough to understand and are very similar to the above p

Where things get more interesting are with the bottom two case items:

  • : (colon) here is used to denote that a switch has been passed into the script that’s expected, however an argument was expected but was not found. In this code block we simply call the usage function to remind the user what the script expects and to exit.
  • \? is simply a question mark but escaped for bash.  This represents that the switch currently being processed is not expected. Again, we just call our usage function.
  • * (asterisk) is not actually used in our sample script but it’s essentially a default which would catch anything that hasn’t been caught by a previous case element. You could use it to combine the above * and ?.


3 Comments

Paul

22-Jan-2020 at 8:00 am

Excellent tutorial!

Mihai

27-Apr-2021 at 11:57 am

Hi,
I’ve spent 1 hour without taking into account that your test syntax might be wrong. Paul said that is an excellent tutorial so that was the point where I was thinking that is something wrong with my shell or getopts syntax or case.

Breaking down your code:
1. There is no such variable $p or $h. I didn’t find anywhere in the official documentation that getops will assign those variables outside the while loop, so in this case your test from p) in which case your code will always execute usage function because $p will never be 80.
2. The test syntax is wrong – you are testing if the variable has the value 80 or 443, and if it has then you will execute the usage function – this is not the behaviour wanted, you will want to execute usage only if the values are not 80 nor 443.
3. Inside the test syntax you need to put your variables inside double-quotes.
4. The syntax after “# Check required switches exist” is not valid because, again, no variables $p or $h exists or declared in case statements, so you need to replace them.

Corrected syntaxes:
– from case statements in p) switch:
“[[ $p == “80” || $p == “443” ]] && usage” will become “[[ “$PORT” == “80” || “$PORT” == “443” ]] || usage”
– Bellow # Check required switches exist
if [ -z “${p}” ] || [ -z “${h}” ]; then
usage
fi

will become

if [ -z “${PORT}” ] || [ -z “${HOST}” ]; then
usage
fi

Please correct your code so everyone will actually consider it, as you state above, a “boilerplate code”.

Thanks,
Mihai

    James Coyle

    24-May-2021 at 7:09 pm

    You’re absolutely right – I’ve updated the post. Thanks for raising it.

Leave a Reply

Visit our advertisers

Quick Poll

Do you use ZFS on Linux?

Visit our advertisers