1

I am trying to use getopts to parse some command-line arguments in bash version 4.2.45. Unfortunately when I run this script with -r1 apple -r2 banana -n hello -k 56 I do not get any output for r1 or r2. e.g.

./script.sh -r1 apple -r2 banana -n hello -k 56
hello 56

Below is script.sh

read1=
read2=
name=
ks=
outdir=
threads=
while getopts "r1:r2:n:k:o:t" OPTION
do
    case $OPTION in
        r1) read1="$OPTARG" ;;
        r2) read2="$OPTARG" ;;
        n) name="$OPTARG" ;;
        k) ks="$OPTARG" ;;
        o) outdir="$OPTARG" ;;
        t) threads="$OPTARG" ;;
    esac
done

echo $read1 $read2 $name $ks

When I change r1->r and r2->x then I see:

apple banana hello 56

as I expected. Are digits really not allowed as options, or is there something else I am missing here?

Dave
  • 329
  • 1
  • 5
  • 16

1 Answers1

2

Short options with a single - can only be a single character. r1: creates a -r option and a -1 option that takes an argument.

If you want long options then switch from getopts to getopt and use the -l option, which will allow you to use --long arguments with two dashes.

./script.sh --r1 apple --r2 banana -n hello -k 56
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks for the suggestion, I tried doing that and now I get `./script.sh: illegal option -- - ./script.sh: illegal option -- -` – Dave Mar 17 '15 at 18:16
  • 1
    Just to clarify, John is suggesting that you, Dave, switch from using bash's `getopts` to using an entirely separate external program called `getopt`. `getopts` does not support long options but `getopt` does. Some of the pros and cons of `getopt` along with a short example can be found [here](http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options). – John1024 Mar 17 '15 at 18:58