Can the command completion for `cd` be modified to only show directories and ignore files?

5,388

Solution 1

Just add

complete -d cd

in your ~/.bashrc (or other bash configuration file).

Solution 2

This should be happening automatically on a typical install on many distros.
If it is not, you're probably missing the bash-completion package:

  • Ubuntu: sudo apt-get install bash-completion
  • Arch: sudo pacman -S bash-completion
Share:
5,388

Related videos on Youtube

chiliNUT
Author by

chiliNUT

Steam big picture mode sucks. Maybe if valve spent more than 5 minutes implementing it, it would work better.

Updated on September 18, 2022

Comments

  • chiliNUT
    chiliNUT over 1 year

    When I am in a directory in bash, and I press cd Space Tab, it shows everything in the directory as a possibility. (Show all 1000 possibilities?) This is really cumbersome when I am in a directory with lots of regular files and relatively few directories.

    So, is it possible to make the choices for autocompletion of cd to only include directories?

    I know I can get a directory listing within a directory by doing

    ls -d */

    but I'm not sure how to proceed from there.

    I am using CentOS 6.6 Final.

  • chiliNUT
    chiliNUT over 9 years
    it works! thanks. I had to type bash after to reload my ~/.bashrc file
  • Tom Zych
    Tom Zych over 9 years
    That's interesting. This is the default behavior on my Debian install, but typing complete doesn't show -d cd or anything like it. Apparently it's been done in some other way here.
  • jimmij
    jimmij over 9 years
    @TomZych There is popular bash completion script, it is very likely that your distro installed it by default.
  • jimmij
    jimmij over 9 years
    @richard One can also just re-type/paste this command in current interactive shell.
  • chiliNUT
    chiliNUT over 9 years
    @richard so typing bash again starts a sub-shell? good to know!
  • ctrl-alt-delor
    ctrl-alt-delor over 9 years
    Yes try typing quit, or look at results of pstree -h.
  • Lie Ryan
    Lie Ryan almost 7 years
    In the rare cases that you have commands in .bashrc that cannot be safely run more than once (e.g. export PATH=$PATH:/blah would create extra /blahs), then you can also run exec bash (or exec $SHELL to be more portable). This creates a new shell, but does not leave the old shell hanging around in the process tree.
  • 4wk_
    4wk_ about 2 years
    On Debian Bullseye 11.2, this is the default for all user EXEPT root. In order to have the same behaviour on user root, you have to manually edit your bashrc file to source the bash_completion package.