Skip to content
GreenSnippets

Parse command-line flags with getopts

Handle -v, -o FILE and -h in a bash script with getopts and a usage message.

Bash
#!/usr/bin/env bash
set -euo pipefail

usage() { echo "Usage: $0 [-v] [-o output] [-h] FILE..." >&2; }

verbose=0
output="result.txt"

while getopts ":vo:h" opt; do
  case "$opt" in
    v) verbose=1 ;;
    o) output="$OPTARG" ;;
    h) usage; exit 0 ;;
    :) echo "Option -$OPTARG requires an argument" >&2; usage; exit 2 ;;
    \?) echo "Unknown option: -$OPTARG" >&2; usage; exit 2 ;;
  esac
done
shift $((OPTIND - 1))

(( $# > 0 )) || { usage; exit 2; }

for file in "$@"; do
  (( verbose )) && echo "Processing $file"
  cat -- "$file" >> "$output"
done

Example / expected output

Output
$ ./merge.sh -v -o all.txt a.txt b.txt

How it works

getopts is built into bash and handles combined short flags like -vo out.txt. A leading colon in the option string enables silent error handling so you can print your own messages. After the loop, shift $((OPTIND-1)) leaves only positional arguments.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.