Notes

How to take options for your Bash Script

Edit on GitHub


Bash Scripting
2 minutes

Overview:

  • The distinction between options (flags) and positional args
  • getopts for short options, with : meaning “takes a value” and $OPTARG holding it
  • Manual while/case loop for long options (GNU getopt mentioned but not walked through)

Options are the flags you pass to a script, like -v or --verbose. Different from positional arguments ($1, $2, etc.) — options can come in any order, can be optional, and usually toggle behavior or carry a value.

Using getopts

Bash has a builtin called getopts that handles short options (single-letter flags like -h, -v, -f filename).

 1#!/bin/bash
 2
 3while getopts "hvf:" opt; do
 4  case $opt in
 5    h) echo "Usage: $0 [-h] [-v] [-f filename]"; exit 0 ;;
 6    v) VERBOSE=true ;;
 7    f) FILENAME="$OPTARG" ;;
 8    \?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
 9  esac
10done

The string "hvf:" tells getopts which flags to accept. A : after a letter means that flag takes a value, which lands in $OPTARG.

Run it like this:

1./script.sh -v -f data.txt

Long options (--verbose)

getopts only handles short options. For GNU-style long options (--verbose, --file=data.txt) you need the external getopt command (note: no s) or you parse manually with a while + case loop over $1.

Manual parsing looks like:

1while [[ $# -gt 0 ]]; do
2  case "$1" in
3    -v|--verbose) VERBOSE=true; shift ;;
4    -f|--file) FILENAME="$2"; shift 2 ;;
5    -h|--help) show_help; exit 0 ;;
6    *) echo "Unknown option: $1" >&2; exit 1 ;;
7  esac
8done

shift drops $1 and shifts everything down, so $2 becomes $1. shift 2 drops two args — useful when the flag took a value.

See also