2

I want to pass 3 parameters with getopts to my shell script. The script requires at least the first 2, the third parameter is optional. If it is not set, its default is used. So that the following would both work:

sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"

I tried to do it like the following, but it constantly ignores my entered parameters.

usage() {
 echo "Usage: Script -a <homedir> -b <threads> -c <string>"
  echo "options:"
                echo "-h      show brief help"

  1>&2; exit 1;
}

string="bla"

while getopts h?d:t:a: args; do
case $args in
    -h|\?)
        usage;
        exit;;
    -a ) homedir=d;;
    -b ) threads=${OPTARG};;
    -c ) string=${OPTARG}
        ((string=="bla" || string=="blubb")) || usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done

I'm new to this getopts, before I just added the parameters in a specific order, which I don't want to do here. I have read a lot questions in here, but unfortenatly didn't find it the way I need it.

I really would appriciate your help here. Thanks:)

1
  • Have you looked at the value of $args inside your while loop? The getops tutorial has some good information; maybe you should check there first. Commented Aug 29, 2016 at 15:41

1 Answer 1

7

You have several mistakes in your script. Most importantly, $args only contains the letter of the option, without the leading dash. Also the option string you gave to getopts (h?d:t:a:) doesn't fit to the options you actually handle (h, ?, a, b, c). Here is a corrected version of the loop:

while getopts "h?c:b:a:" args; do
case $args in
    h|\?)
        usage;
        exit;;
    a ) homedir=d;;
    b ) threads=${OPTARG};;
    c ) string=${OPTARG}
        echo "Entered string: $string"
        [[ $string=="bla" || $string=="blubb" ]] && usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much
You may consider to mark the answer as "correct", if it solved your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.