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 and it will expect the above mentioned parameters to be passed in to work. -p 443 -h -f

getopts Example


# 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
            [[ $PORT != "80" && $PORT != "443" ]] && usage
            echo "ERROR: Option -$OPTARG requires an argument"
            echo "ERROR: Invalid option -$OPTARG"
shift $((OPTIND-1))

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

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 -p. The colon specifies that an attribute must follow the switch, for example -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 -p 443 -h -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 ?.

Visit our advertisers

Quick Poll

How often do you change the password for the computer(s) you use?

Visit our advertisers