autocompletion with wildcards for cd in bash

Using bash on ubuntu (debian jessie/sid) I’m not sure why I can’t do tab completion of a wildcard with a builtin command.

for example, suppose my current working directory contains the following subdirectories..

% ls -l
drwxr-xr-x 2 userX 4096 2016-08-31 11:46:40 0830a/
drwxr-xr-x 2 userX 4096 2016-08-31 11:46:52 0830b/
drwxr-xr-x 2 userX 4096 2016-08-31 11:47:33 0831a/
drwxr-xr-x 2 userX 4096 2016-08-31 11:47:18 0831b/
drwxr-xr-x 2 userX 4096 2016-08-31 11:50:38 z0830z/

I am able to hit after typing ‘ls -l *31a’ and get the completion to occur..

ls -l *31a<tab>

completes to..

ls -l 0831a

however, if I attempt the same with the builtin ‘cd’ command, it will not complete..

cd *31a<tab>

.. will not complete

Also, using a trailing wildcard fails as well..

cd z*<tab>

.. will not complete

Interestingly, completion without a wildcard character works OK for the builtins. For example, I am able make this completion work OK:

cd z<tab>

is completed to..

cd z0830z/

furthermore, I can use the ‘cd *31a’ command as-is and have it succeed (so long as it is unique). But I want the expansion to occur so I know for sure what I’m cd-ing into.

My .inputrc contains this..

$if Bash
  Space: magic-space
  set mark-directories on
  set mark-symlinked-directories on
  set completion-ignore-case off
  set show-all-if-ambiguous on

I don’t have a ~/.bash_completion file. I do have /etc/bash_completion, which only does a source of /usr/share/bash-completion/bash_completion. That latter file is a bit long so I won’t include it here.

My ultimate goal is to be able to have wildcard completion work for the cd command.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I’m fighting with the same problem. As @Gilles mentioned, there is no real bash-based solution right now.

Since bash-completion doesn’t really add much functionality to cd (AFAIK only the use of $CDPATH directories), so if you’re not using that then you can add this to your ~/.bashrc:

compopt -o bashdefault cd

This will reset the behavior of the cd completion to default (where wildcard completion works), and will not change anything else.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply