Parsing Command-Line Arguments in Bash

Bash scripts often need to read command-line arguments. For simple scripts, you can use positional parameters such as $1, $2 and $@.

Simple positional arguments

#!/bin/bash

echo "First argument: $1"
echo "Second argument: $2"

Loop through all arguments

for arg in "$@"; do
  echo "Argument: $arg"
done

Basic option handling

while getopts "f:v" opt; do
  case "$opt" in
    f) file="$OPTARG" ;;
    v) verbose=1 ;;
  esac
done

getopts is useful for small scripts that need flags such as -v or options with values such as -f file.txt.

Leave a Comment