Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
            case $option in
                    #start my server
                    local cdir="~/mydirectory"
                    local cdir_arg=""
                    case $OPTARG in
                            local cdir_arg="anotherdirectory"
                    local cdir="${cdir}${cdir_arg}"
                    cd $cdir
                    echo 'This function doesnt have Super Cow Powers'
                    return 1

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
up vote 7 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

Your Answer


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.