Script template

The following shell script doesn’t do anything interesting by itself but it is a very useful bit of boiler plate for parsing command line options.

#!/bin/bash
#
# sh-template.sh
#
# 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 <http://www.gnu.org/licenses/>
#
#  04 Jul 17   0.1   - Initial version - MEJT
#
_count=0
 
#-- Scan command line arguments
while test $# -gt 0do
  case "$1" in
  --help)
    echo "syntax: $0 [OPTION]... [FILE]..."
    echo "  -p, --param <parameter>     Set parameter"
    echo "  -o, --opt                   Describe opt here."
    echo "      --noopt                 Don't do opt."
    exit 0 ;;
  --opt) # Set option
    opt=true ;;
  --noopt) # Clear option
    opt=false ;;
  -p|--param) # An example of an option with a parameter
    case $2 in
    -*|""# Blank or another qualifier
      echo "$0: Parameter not specified."
      exit -1 ;;
    *)
      _parameter=$2
      shift ;;
    esac ;;
  -*) # Unrecognized qualifier!
    echo "$0: unrecognized option '$1'"
    echo "Try '$0 --help' for more information."
    exit 0 ;;
  *) # Append each argument to args[] (preserving quoted strings).
    _args[$_count]=$1
    _count=$((_count+1)) ;;
  esac
  shift
done
 
#-- The main body of the code starts here.

echo "$_parameter"
for _argv in "${_args[@]}"do # Repeat for all arguments.
  echo "$_argv"
  if [ $? -ne 0 ]then breakfi
done

#-- Finally exit!
exit $?

Advertisements
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s