Bash · lekcja 22 z 30 · Pliki i błędyCzytaj opcje
getopts czyta -l 95 i -q, a shift usuwa je z listy argumentów.
22-options.sh Pobierz 22-options.sh
#!/usr/app/TurboShell/bin/bash
usage() {
echo "użycie: 22-options.sh [-l LIMIT] [-q] NAZWA"
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: zajęte $used procent, limit $limit"
((used < limit))
Terminal
$ bash 22-options.sh -l 95 media; echo "kod wyjścia $?"
media: zajęte 93 procent, limit 95
kod wyjścia 0
$ bash 22-options.sh -q media; echo "kod wyjścia $?"
kod wyjścia 1
$ bash 22-options.sh -x 2>/dev/null; echo "kod wyjścia $?"
użycie: 22-options.sh [-l LIMIT] [-q] NAZWA
kod wyjścia 2Ćwiczenie
Dodaj -h, które wypisze pomoc i zakończy z kodem 0.