NASutils Knowledge BaseUnofficialPolski

Bash · lesson 22 of 30 · Files and errorsRead options

getopts reads -l 95 and -q; shift leaves the rest.

Programming on the NAS › Bash in 30 lessons

22-options.sh Download 22-options.sh

#!/usr/app/TurboShell/bin/bash
usage() {
  echo "usage: 22-options.sh [-l LIMIT] [-q] NAME"
  exit 2
}

limit=90 quiet=no
while getopts 'l:q' option; do
  case $option in
    l) limit=$OPTARG ;;
    q) quiet=yes ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1))
(($# == 1)) || usage
[[ $limit =~ ^[1-9][0-9]?$ ]] || usage

used=93
[[ $quiet == yes ]] || echo "$1: $used percent, limit $limit"
((used < limit))

Terminal

$ bash 22-options.sh -l 95 media; echo "exit code $?"
media: 93 percent, limit 95
exit code 0
$ bash 22-options.sh -q media; echo "exit code $?"
exit code 1
$ bash 22-options.sh -x 2>/dev/null; echo "exit code $?"
usage: 22-options.sh [-l LIMIT] [-q] NAME
exit code 2

Exercise

Add -h, which prints the usage and ends with 0.