Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

When I try to run my bash function, defined in .bashrc, for a second time in the same terminal, it doesn't work.

The code is the following:

function nos (){
    local option
        while getopts cs option
            do
            case $option in
                s)
                    #start my server
                ;;
                c)
                    local cdir="~/mydirectory"
                    local cdir_arg=""
                    case $OPTARG in
                        p)
                            local cdir_arg="anotherdirectory"
                        ;;
                    esac
                    local cdir="${cdir}${cdir_arg}"
                    cd $cdir
                    ;;
                *)
                    echo 'This function doesnt have Super Cow Powers'
                    return 1
                ;;
            esac
    done
}

I run this:

nos -c

it goes to ~/mydirectory

ok, worked.

but then I do this:

cd ~
nos -c

and nothing happens.

share|improve this question
    
I can totally reproduce this and I cannot understand why it is happening. –  hakermania Sep 22 '12 at 22:15
add comment

1 Answer 1

up vote 6 down vote accepted

The getopts builtin keeps track of how far it's gone through the options through the OPTIND variable. The second time you run the function, $OPTIND has retained its value from the previous call, so the shell thinks it's already finished processing the options. See the description of getopts in the manual for more information.

Declare OPTIND and OPTARG as local to the function.

There's another mistake in your function, which is that ~ isn't expanded between double quotes. Make that local cdir=~/mydirectory or local cdir="$HOME/mydirectory"

share|improve this answer
    
I'll try that, and ty for the correction. Though this part of the code is just an example, to simplify my question, I didn't know about that. –  RjQuery Sep 23 '12 at 0:27
    
Worked! Thank you very much. –  RjQuery Sep 23 '12 at 4:37
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.