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
  • 12,077
  • 7
  • 41
  • 52

2 Answers2

2

Building my own cd function with completion

Using an associative array for storing some paths.

First the command:

mycd() { [ -v 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='(
     ["docs"]="/usr/share/doc"
     ["home"]="$HOME"
     ["logs"]="/var/log"
     ["proc"]="/proc"
     ["root"]="/"
     ["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
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
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
  • 12,077
  • 7
  • 41
  • 52