Search code examples
bashargumentsgetopts

Restricting Bash Arguments?


Here is my bash script, very simple with no meat in it at the moment:

#!/bin/bash

NO_ARGUMENTS=0
ARG_ERROR=10

if [ $# -eq "$NO_ARGUMENTS" ]
then
  echo "Usage: `basename $0` options (-h -C -m)"
  exit $ARG_ERROR
fi

helpscreen()
{
echo
echo "========================"
echo "Help Screen:"
echo "Available Arguments:"
echo "-h - Displays this screen"
echo "-C - Complete Install"
echo "-m - Minimal Install"
echo "========================="
echo 
}

completeinstall()
{
echo "Complete Install Initiating"
}

minimalinstall()
{
echo "Minimal Install Initiating"
}

while getopts ":hCm" Option
do
  case $Option in
    h) helpscreen;;
    C) completeinstall;;
    m) minimalinstall;;
    *) echo "Option Not Available.";;
  esac
done

exit

As you can see it just runs the options when ./test.sh -h, -C, or -m is chosen. My problem is that a user can select -Cm and have it run through both the complete and minimal install. How can I edit this in order to stop such an event from happening/restrict the options.


Solution

  • Don't loop, since you only care about one option.

    getopts ":hCm" Option
    case $Option in
      h) helpscreen;;
      C) completeinstall;;
      m) minimalinstall;;
      *) echo "Option Not Available.";;
    esac
    

    Or add a break to each case.

    while getopts ":hCm" Option
    do
      case $Option in
        h) helpscreen;      break;;
        C) completeinstall; break;;
        m) minimalinstall;  break;;
        *) echo "Option Not Available.";;
      esac
    done
    
    exit