Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This is my first question.

I'm trying to make a small script with options and I'm using getopts to do it. The weird thing is:

The argument don't get assigned to the variable or it always enter the if codeblock (that seems the problem).

Here is the script:

#!/bin/bash

function work () {
    echo "It Works" }

function help () {
    echo "Print some help and options" }

while getopts ha:b: OPT; do
    case $OPT in
        -h)
            help
            exit
            ;;
        -a)
        OPTA=$OPTARG
        ;;
        -b)
        OPTB=$OPTARG
            ;;
        \?)
        help
            break
            ;;
    esac done

echo $OPTB

if  [[ -z $OPTB ]]; then
    echo "ERROR. Needs OPTB"
fi

if [[ -n $OPTB ]]; then
    echo "All OK untill here"
    work
fi

It allways prints the ERROR message.

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

getopts removes the "-" sign from the options.

So you need:

while getopts ha:b: OPT; do
    case $OPT in
        h)
            help
            exit
            ;;
        a)

 ....

And remember to clear your variables before calling getopts (unset OPTA OPTB) as they may be in the environment received by your script. Also please consider the case of whether calling the script with -b "" is valid or not as your [[ -z $OPTB ]] doesn't differentiate "no -b option" from "-b option with empty argument".

share|improve this answer
    
Thank you, I did all that you said. It worked. –  NotFromBrooklyn Oct 4 '12 at 12:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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