Bash – Prevent path autocompletion from using CDPATH in bash

autocompletebash

On my Mac, bash (version 3.2.53(1)) autocompletes command-line arguments using files only in the current directory.

On a Linux machine at work, bash (version 4.1.2(1)) autocompletes command-line arguments using files from the current directory and parent directories.

For example, given the directory tree:

/home/pjl/
    bin/
    foo/
        book/

If on my Mac I do:

$ cd foo
$ cd b<TAB>
$ cd book

bash autocompletes only to book. However, when I'm on the Linux machine and do the exact same thing:

$ cd foo
$ cd b<TAB>
bin book
$ cd b

bash presents two choices: book from the current directory and bin from the parent directory.

How can make bash autocomplete only using the current directory (like it does on my Mac)?

On both machines, I do have CDPATH set to:

.:..:../..:../../..:../../../..:../../../../..:/home/pjl/src:/home/pjl

and if I unset CDPATH on the Linux machine, then bash autocompletes using only the current directory (which is what I want); hence I know the bash on Linux is using CDPATH.

But how can I keep CDPATH set (so cd'ing works as before), but not have bash use CDPATH when doing autocompletion?


An alternate acceptable behavior would be to have autocompletion favor the current directory and use CDPATH if and only if nothing in the current directory matches.

Best Answer

The correct way would be to use the following in your ~/.bashrc as @Gilles suggested above (shorter version here):

_my_cd () { CDPATH= _cd "$@";}

A better way would be to check CDPATH if and only if no matches are found locally:

_my_cd () { CDPATH= _cd "$@"; if [ -z "$COMPREPLY" ]; then _cd "$@"; fi;}

This way you get the functionality of programmable completion without it being a nuisance. Do not forget

complete -F _my_cd cd

For some reason /usr/share/bash-completion/bash_completion has -o nospace for cd (even though nospace seems to be default), so you might as well have:

complete -F _my_cd -o nospace cd
Related Question