Bash 5 reference · Shell Builtins and Syntax

getopts (Bash builtin)

Parse short command-line options such as -v and -o FILE in scripts, with errors for unknown options.

Bash 5

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

while getopts ":vo:" opt; do case $opt in ...; esac; done; shift $((OPTIND - 1))

Parameters

ParameterDescription
":vo:" Leading : for silent errors; o: takes an argument.
$OPTARG The option's argument.
$OPTIND Index of the next argument.

Examples

Options with and without arguments
parse() {
  local OPTIND opt verbose=0 out=-
  while getopts ':vo:' opt; do
    case $opt in v) verbose=1 ;; o) out=$OPTARG ;; *) echo "bad option -$OPTARG"; return 2 ;; esac
  done
  shift $((OPTIND - 1))
  echo "verbose=$verbose out=$out rest=$*"
}
parse -v -o report.txt a b
parse -x || echo "status $?"

Output

verbose=1 out=report.txt rest=a b
bad option -x
status 2

Run this on your computer — see “Get Started” for setup.

A missing option argument
opts() {
  local OPTIND opt
  while getopts ':n:' opt; do
    case $opt in
      n) echo "name=$OPTARG" ;;
      :) echo "-$OPTARG needs a value"; return 2 ;;
    esac
  done
}
opts -n api
opts -n || echo "status $?"

Output

name=api
-n needs a value
status 2

Run this on your computer — see “Get Started” for setup.

Was this page helpful?