#!/bin/sh set -u #abort when undefined vars are used # Frobnicator # # Copyright (C) 2016 Assaf Gordon # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . die() { BASE=$(basename "$0") echo "$BASE: error: $*" >&2 exit 1 } show_help_and_exit() { BASE=$(basename "$0") echo \ "Frobnicator - fronbnicates files Usage: $BASE [OPTIONS] FILE Mandatory arguments to long options are mandatory for short options too. Options: -h, --help = This help screen. -v, --verbose = Be verbose. -n, --number=N = example option with value " exit } parse_cmdline_options() { verbose= number= input= while test $# != 0 ; do case "$1" in -h|--h|--he|--hel|--help) show_help_and_exit ;; -v|--v|--ve|--ver|--verb|--verbo|--verbos|--verbose) verbose=1 ;; # The user has specied the value as a separate # parameter, e.g.: # ./script --number 4 # so fetch the next param -n|--n|--nu|--num|--numb|--numbe|--number) shift test $# != 0 || die "missing value for -n/--number parameter" number="$1" ;; # The user specified a single-letter option with # the value immediately following it, e.g.: # ./script -n4 # So remove the "-n" prefix and keep the value -n*) number=${1#-n} ;; # The user specified a long option with # the value immediately following it, e.g.: # ./script --number=4 # So remove the prefix and keep the value --n=*|--nu=*|--num=*|--numb=*|--numbe=*|--number=*) number=${1#*=} ;; --) shift break;; -*) die "Unknown option '$1'. See --help for help." ;; *) break;; esac shift done # Parameters input validation if test "$number" ; then expr match "$number" '^[0-9][0-9]*$' >/dev/null \ || die "invalid --number value '$number'" fi test $# -eq 0 \ && die "missing input file. See --help for more information." test $# -ge 2 \ && die "extra operand ($2). See --help for help." # first parameter - filename input="$1" # optional input validation #test -e "$input" \ # || die "input file '$input' not found" } ## ## Program starts here ## parse_cmdline_options "$@" if test "$verbose" ; then echo "Processing file '$input'" test "$number" \ && echo "optional number = $number" \ || echo "optional number not set" fi