1

I am trying to define a bash function, mycd. This function uses an associative array mycdar. If the key exists in the array the function will change directory to the corresponding value of the key. If the key doesn't exist it will change to the dir provided in the command line.

What I would like to do is to have completion for this function, from both they keys of the associated array or from the folders existing in the current directory.

Thank you.

skeept
  • 11,437
  • 6
  • 37
  • 51

2 Answers2

2

First the command:

mycd() { [ "${mycdar[$1]}" ] && cd "${mycdar[$1]}" || cd "$1"; }

Second the completion command

_mycd() {
    local cur;
    _cd ;
    _get_comp_words_by_ref cur;
    COMPREPLY=($(
        printf "%s\n" "${!mycdar[@]}" |
            grep ^$cur)
        ${COMPREPLY[@]});
    }

One array:

declare -A mycdar
mycdar['docs']=/usr/share/doc
mycdar['home']=$HOME
mycdar['logs']=/var/log
mycdar['proc']=/proc
mycdar['root']=/
mycdar['tmp']=/tmp

Than finaly the bind:

complete -F _mycd -o nospace mycd

Or to permit standard path building behaviour:

complete -F _mycd -o nospace -o plusdirs mycd

But this will not work against our mycdar path array.

F. Hauri
  • 58,205
  • 15
  • 105
  • 122
1

It turns out that there is an option that to the complete function that does exactly what is asked:

complete -o plusdirs -o nospace -F _mycd mycd

In this case _mycd just returns matching elements from the keys of the associative array.

skeept
  • 11,437
  • 6
  • 37
  • 51