← Back to all snippets
BASH

Parse Command-Line Arguments with `getopts`

Discover how to effectively parse command-line arguments using Bash's built-in `getopts` for creating flexible and user-friendly shell scripts with options.

#!/bin/bash

# Default values
VERBOSE=0
OUTPUT_FILE=""

# Parse options
while getopts "vo:" opt; do
  case $opt in
    v)
      VERBOSE=1
      ;;
    o)
      OUTPUT_FILE="$OPTARG"
      ;;
    \?)
      echo "Usage: $0 [-v] [-o output_file] <input_file>" >&2
      exit 1
      ;;
  esac
done

# Shift positional parameters so that $1 refers to the first non-option argument
shift $((OPTIND-1))

INPUT_FILE="$1"

if [ -z "$INPUT_FILE" ]; then
  echo "Error: Input file is required." >&2
  echo "Usage: $0 [-v] [-o output_file] <input_file>" >&2
  exit 1
fi

echo "Input file: $INPUT_FILE"
[ "$VERBOSE" -eq 1 ] && echo "Verbose mode is ON."
[ -n "$OUTPUT_FILE" ] && echo "Output file: $OUTPUT_FILE"

# Example usage with parsed variables:
# cat "$INPUT_FILE" > "$OUTPUT_FILE"
How it works: This script demonstrates how to parse short command-line options using `getopts`. It defines options like `-v` for verbose mode and `-o` for an output file, which accepts an argument. The `while` loop iterates through options, and a `case` statement handles each one. After parsing, `shift` adjusts positional parameters, allowing the script to easily access non-option arguments.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs