1

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
Cyrus
  • 84,225
  • 14
  • 89
  • 153
upendra
  • 2,141
  • 9
  • 39
  • 64

1 Answers1

3

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!
  • How do i assign a files to `cagefile` and `knownlinc` ? Basically I want to run my script like this `sh evolinc-part-I.sh -c cuffcompare.gtf -g Brassica_genome.fa -r Brassica_cds.fa -b TE_transcripts.fa` (these all are the mandatory arguments) and -t Brassica_cage.gtf (cagefile) and -x Brassica_known.gff (these two are optionals)` – upendra Jan 06 '16 at 04:54
  • I don't understand. I think you mix up *options* and *arguments*. A cmd like `test.sh -t -a test` has *two* options `t` and `a` but only `a` has an argument. If you define in getopts something like `getopts "t:" opt` the *argument* for `t` is already mandatory. –  Jan 06 '16 at 07:33