Parse command-line flags with getopts
Handle -v, -o FILE and -h in a bash script with getopts and a usage message.
- Bash
- GreenSnippets
- MIT
#!/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"
doneExample / expected output
$ ./merge.sh -v -o all.txt a.txt b.txtHow 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.
Related snippets
- Python Tested
Command-line tool skeleton with argparse
A small CLI with a positional argument, flags, a main function and proper exit codes.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.
- Bash
Delete local Git branches that are already merged
Clean up merged local branches safely, excluding main, master, develop and the current branch.
- Bash
Safe header for Bash scripts
Fail fast on errors, unset variables and broken pipes, and clean up temp files with a trap.

