Luca Moscato
Luca Moscato

Reputation: 21

getopts with all optional arguments

In order to run a bash script I need some arguments and flags, since the requirements are pretty tricky I've chosen to use a getopt function like this

while getopts ":s:g:r" o; do
    case "${o}" in
        s)
        # Variables that require value            
        VALUE1=${OPTARG}
        ;;
        g)
        # Variables that require value
        MGROUP=${OPTARG}
        ;;
        r)
        # Variables that, if present, set just a flag
        ASROOT=1
        ;;
        *)
        echo "Usage: ./myscript.sh -s value1 -g value2 -r"
        ;;
    esac
done

I would like to have all parameters optional so I can write some conditions later in my code, and first two (s and g) with an arguments, the third (r) is only a optional flag. In the future I may need to add additional parametrers, always optional. Any advice?

Upvotes: 1

Views: 2696

Answers (2)

chrissy
chrissy

Reputation: 21

Sample script illustrating optional arguments with bash getopts in a style similar to mysql client. "--" is also supported.

Usage: script.sh [-u ] [-p | -p] [--] arg1 arg2 ...

#!/bin/bash
#
# Sample script illustrating optional arguments with bash getopts in
#   a style similar to mysql client.  "--" is also supported.
#
# [email protected] - 5-Oct-2019 - Distribute/use without restriction.
#

# Defaults
username="$(whoami)"
unset password

while getopts ":u:p:" arg; do
  case $arg in
      u)  # Username
      username="$OPTARG"
      ;;
      p)  # Password
      thisarg=$((OPTIND - 1)); thisarg="${!thisarg}"; thisarg="${thisarg:2}"

      if [[ ! -z $OPTARG ]] && [[ "$OPTARG" != "$thisarg" ]]; then
          unset password
          OPTIND=$((OPTIND - 1))
      else
          password="$thisarg"
      fi
      if [[ -z $password ]]; then
          read -s -p "Password: " password
          echo
      fi
      ;;
      \?)
      # Request Help
      echo "Sorry that I can be of no help."
      ;;
      *)
      # Deal with option at end of line
      OPTION=$((OPTIND - 1)); OPTION="${!OPTION}"
      case $OPTION in
          --)
          # Add support for --
          break
          ;;
          -p)
          # Option with optional argument
          unset password
          read -s -p "Password: " password
          echo
          ;;
          *)
          # Invalid argument
          echo "Error; Invalid option \"$OPT\"." >&2
          ;;
      esac
      ;;
  esac
done
shift $((OPTIND -1))

echo "Username: $username"
echo "Password: $password"
echo
echo "Remaining arguments:$*"
echo

Upvotes: 2

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19305

The optional parameter are optional to make mandatory check VALUE1 and MGROUP. For example:

[[ -n $VALUE1 && -n $MGROUP ]] || {
    echo "mandatory paramter missing"
    exit 1
}

getopts

Upvotes: 1

Related Questions