6

I have a question similar to this one, but different: I want bash to use a glob expansion in auto-completion, if possible. For example, I would like

$ ls *2.<TAB>

To give me:

$ ls mydoc2.
mydoc2.pdf mydoc2.tex mydoc2.txt

I face this situation quite often. In the above example I used the short prefix “mydoc,” but the actual ones are often quite long. Is this possible?

I understand *2.* would expand with C-x*, but that's a different function, which isn't suitable in this situation (because I need to choose just one file from the list of the files that match the glob).

4

The best method to simulate this auto-completion behavior is to enable the show-all-if-ambiguous readline variable (to display the possible completions if more than one match is found), then invoke the completion with the glob-complete-word readline command (to perform the glob pathname expansion).


# 1: Enable `show-all-if-ambiguous` in ~/.inputrc

set show-all-if-ambiguous on

show-all-if-ambiguous: This alters the default behavior of the completion functions. If set to ‘on’, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. The default value is ‘off’.


# 2a: Check to ensure that `glob-complete-word` is bound.

$ bind -q "glob-complete-word"

glob-complete-word can be invoked via "\eg".


# 2b: If unbound, bind `glob-complete-word` to "\eg".

$ bind '"\eg":glob-complete-word'

glob-complete-word (M-g): The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching file names for possible completions.


# 3: Trigger the autocompletion with <META-g> or <ESC-g>

# META => alt      (Windows/Linux)
# META => option   (OSX)

$ ls *2.<META-g>     

# possible completions will be listed (show-all-if-ambiguous)   
mydoc2.pdf mydoc2.tex mydoc2.txt

# glob pathname completion will be performed (glob-complete-word)
$ ls mydoc2.  
  • 1
    Thank you! Your method works! One question: I don't understand why show-all-if-ambiguous is necessary. In other words, what is glob-complete-word supposed to do on its own? On my terminal it doesn't do anything without show-all-if-ambiguous of readline. – Ryo Sep 12 '17 at 9:38
  • @Ryo – glob-complete-word does the actual completing piece. So, in this example, it will convert *2. to mydoc2.. show-all-if-ambiguous is what handles listing the possible completions (mydoc2.pdf mydoc2.tex mydoc2.txt) for ambiguous (i.e. more than 1) matches. If you invoke <META-g> multiple times with show-all-if-ambiguous disabled, most shells will usually show the completion list; this option just makes it more fluid as it works on the first invocation. – Travis Clarke Sep 13 '17 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.