Wednesday 17 March 2010

Options in bash scripts part 2

Here's a little demo script I wrote, which reads a couple of options from the command line and performs some basic error checking.  It also makes use of regex matching using

if [[ $test_variable =~ $a_regular_expression ]]; then
  # you have matched the regular expression
else
  # you haven't matched the regular expression
fi

Here's the script:

#! /bin/bash

#TODO: Fill in help message
usage()
{
cat << EOF
usage: $0 FILENAME NPROCS options

This script reads command-line args and dumps them to stdout

# describe arguments here

OPTIONS:
 -t    blah
 -r    blah
EOF
}

# Set default values for variables
ram=1G
time="48:00:00"

#TODO: This time format only specifies that times are
#  numbers up to 49:00:00.  Correct this so that
#  only times up to 48:00:00 are allowed
time_format='[0-4][0-9]:[0-5][0-9]:[0-5][0-9]'

# Read command-line arguments and set variables
while getopts "r:t:h?" OPTION
do
 case $OPTION in
  ?)
   usage
   exit 1
   ;;
  h)
   usage
   exit 1
   ;;
  r)
   ram="$OPTARG"G

   # TODO: Check that ram is an integer
   #  within the range 1-12

   # Remove "used" argument
   shift $((OPTIND-1)); OPTIND=1
   ;;
  t)
   time=$OPTARG

   # Check that time format is correct
   if [[ $OPTARG =~ $time_format ]]; then
    time=$OPTARG
   else
    echo "ERROR: Time format wrong"
    exit
   fi

   # Remove "used" argument
   shift $((OPTIND-1)); OPTIND=1
   ;;
 esac
done

filename=$1
# TODO: Check that filename is a valid file identifier

nprocs=$2
# TODO: Check that nprocs is a valid integer

# Dump all variable values to stdout
echo time=$time
echo ram=$ram
echo filename=$filename
echo nprocs=$nprocs

No comments:

Post a Comment