2

Say I have a directory like so:

 foo/
   bar.js
   bar/

if I cd into foo and then type "ba" and then hit tab, I won't get completion because a file name overlaps with a folder.

Is there a key I can hold with tab that will just give me the folder (or the file?)

4
  • 2
    Not in bash. zsh completion behaves closer to what you want.
    – jordanm
    Feb 22, 2017 at 2:13
  • 1
    @jordanm Bash has had selective completion for over a decade (a bit more than half as long as zsh has had it). Feb 22, 2017 at 21:17
  • @jordanm riiiight then can you answer the original question? Feb 22, 2017 at 22:28
  • still diggin' this question Sep 20, 2017 at 21:06

2 Answers 2

1

TL,DR: add . /etc/bash_completion to your .bashrc.

To answer the exact question you asked, there is no such built-in commands. Bash has commands to complete various kinds of objects (file names, user names, variable names, etc.) but not one that's restricted to directories.

However, unless you're running an antique version of bash, you can use context-sensitive completion, a feature added in version 2.04 which was released in 2000. Some distributions enable it by default; for others you need to install the bash-completion package and activate it in your ~/.bashrc. Most distributions provide a package called bash-completion and put the activation script in /etc/bash_completion, i.e. your .bashrc should contain the line

. /etc/bash_completion

After this, if you enter cd and press Tab, only directory names will be completed.

If you have a non-ancient version of bash (≥4.0), you can put shopt -s autocd in your .bashrc, and after this you can omit the cd command, so you can write just bar instead of cd bar. Tab completion will complete both command names from $PATH and directory names from the current directory (and $CDPATH) on the first word of the line.

Bash 4.0 also lets you write your own command line edition functions (earlier versions kinda did but you had to jump through hoops). So if you really want you could do that. How to customize Bash command completion? has a relatively complex example; search for READLINE_LINE and complete to find other examples.

1

The reason why you are not getting any completions after typing ba is because you did not precede ba with the cd command. Bash realises that neither typing bar.js<ENTER> nor bar<ENTER> would make sense (one is a directory while another file bar.js is either not in $PATH and/or does not have the executable permission set), so it does not give you any completions at all.

However, if you precede the directory name with a cd, bash will see bar fits, and no other name does, and will perform a full completion:

$ ls
bar  bar.js
$ cd <TAB>

At which point the prompt will transform into

$ cd bar/ # This line

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .