Script Arguments

View saved

Positional parameters

$1, $2, … are arguments. $0 is the script name. $# is the count.

#!/usr/bin/env bash
echo "Script: $0"
echo "Count: $#"
echo "First: ${1:-}"

All arguments

"$@" preserves each argument safely. Prefer it over $*.

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

shift

Drop $1 and renumber the rest—handy while parsing options.

while [[ $# -gt 0 ]]; do
  echo "Processing $1"
  shift
done

getopts peek

For short flags, getopts is built in. For complex CLIs, consider a dedicated parser later.

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

Comments

One comment per signed-in account. Comments are saved with this page’s URL.