Search code examples
bashgetopts

How to add optional arguments in getopts in bash?


I would like to add couple of optional arguments in getopts. For example, for the below code, i want to add 2 optional arguments - cagefile and knownlinc. How can i do that by modifying this code?

while getopts ":b:c:g:hr:" opt; do
  case $opt in
    b)
      blastfile=$OPTARG
      ;;
    c)
      comparefile=$OPTARG
      ;;
    h)
      usage
      exit 1
      ;;
    g)
     referencegenome=$OPTARG
      ;;
    r)
     referenceCDS=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

Solution

  • A simple solution that supports longopts would be to manually parse the remaining arguments after your getopts command. Like this:

    #!/bin/bash
    
    # parse basic commands (only example) 
    while getopts "t:" opt; do
        case "$opt" in
        t)  TVAR="$OPTARG"
            ;;
        *)  echo "Illegal argument."; exit 1
            ;;
        esac
    done
    echo "TVAR set to: $TVAR"
    
    # shift to remaining arguments 
    shift $(expr $OPTIND - 1 )
    
    while test $# -gt 0; do
        [ "$1" == "cagefile" ] && echo "cagefile found!"
        [ "$1" == "knownlinc" ] && echo "knownlinc found!"
        shift
    done
    

    Output would be..

    » ./test.sh
    » ./test.sh -t
    ./test.sh: option requires an argument -- t
    Illegal argument.
    » ./test.sh -t 2
    TVAR set to: 2
    » ./test.sh -t 2 cagefile
    TVAR set to: 2
    cagefile found!
    » ./test.sh -t 2 cagefile knownlinc
    TVAR set to: 2
    cagefile found!
    knownlinc found!