Required option getopts linux

rocketmanu picture rocketmanu · Oct 11, 2014 · Viewed 11.5k times · Source

I have to write a bash script:

    schedsim.sh [-h] [-c #CPUs ] -i pathfile

h and c are optional options. i is required, when run script if it doesn't have i option -> error message.

How to make a required option in getopts? Thanks!

another question: how to make default value for an argument of option? say, if c isn't provided argument -> default value of argument of c is 1.

Answer

Olivier Diotte picture Olivier Diotte · Oct 12, 2014

You cannot make an argument required as in "the getopts builtin returns an error if that argument is missing".

But it is trivial to make a function that does that yourself:

#!/bin/bash

function parseArguments () {
  local b_hasA=0
  local b_hasB=0
  local b_hasC=0

  while getopts 'a:b::c' opt "$@"; do
    case $opt in
    'a')
      b_hasA=1
      ;;
    'b')
      b_hasB=1
      ;;
    'c')
      b_hasC=1
      ;;
    esac
  done

  if [ $b_hasA -ne 0 ]; then
    echo "A present"
  fi
  if [ $b_hasB -ne 0 ]; then
    echo "B present"
  fi
  if [ $b_hasC -ne 0 ]; then
    echo "C present"
  else
    echo "Error: C absent"
    exit 1
  fi
}

#Quotes required to avoid removing characters in $IFS from arguments
parseArguments "$@"

Tests:

$ ./test.bash -c
C present

$ ./test.bash -b
./test.bash: option requires an argument -- b
Error: C absent

$ ./test.bash -b foo
B present
Error: C absent