1

I have a script:

#!/bin/sh

function usage() {
    cat << EOF >&2
Usage: $0 [-h] [-rs <start_num>] [-re <end_num>]

-h:  help: displays list of options for command $0
-rs<int>: range start: should be the number to go from - the lower of the two ranges. <int>
-re<int>: range end: should be the number to add up to - the highest of the two ranges. <int>
EOF
    exit 1
}

function addition() {
    sum=0

    for number in "$@"; do
        sum=$(( sum + number))
    done

    # set defaults    
    rangeStart=0
    rangeEnd=0
    error=false

    # loop arguments
    OPTIND=1

    while getopts rs:re:h: o; do
        case $o in
            rs) rangeStart=$OPTARG;;
            re) rangeEnd=$OPTARG;;
            h) usage;;
            *) error=true;;
        esac
    done
    shift $((OPTIND - 1))

    echo $rangeStart
    echo $rangeEnd

    if [ "$error" = true ] ; then
        echo 'Invalid argument passed. See addition -h for usage.'
    else
        echo 'Total: '$sum
    fi
}

At the moment, I'm just trying to add command arguments so user can type:

$ addition -rs 4 -re 10 

and it loops from 4 up to 10 (so adding 4 + 5 + 6 + 7 + 8 + 9 + 10) and outputs that total.

but doing the above returns output of:

0
0
Invalid argument passed. See addition -h for usage.

so it's not recognising my params. And when I alter the command to:

$ addition -rs4 -re10 

it outputs the same.. what am I doing wrong in my script?

1

The getopts builtin can only handle single-character options; you have to use something like

getopts 's:e:h'

I've also dropped the colon after h, as you probably don't want an argument for -h.

  • I did want an argument for -h to be --help - ok so I changed to s:e and that does work. Wasn't aware it doesn't support more than one char per option. Ok so how do I make it so it's --range-start= ? – treyBake Sep 4 '18 at 13:50
  • 1
    This article talks about long options. – Benjamin W. Sep 4 '18 at 13:56
  • After checking out the article I've got my script working with the --long-option :) thank you :) - as this directly answers my question, will accept :) – treyBake Sep 4 '18 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.