Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I've got a simple command named th. I've got a bash-completion file for it that goes as follows:

_th()  {
  local curr=${COMP_WORDS[COMP_CWORD]}
  COMPREPLY=( $(compgen -f -X '!*.@(tar|tar.xz|tar.bz2|tar.gz|tbz|tgz)' -- "$curr") )
complete -F _th -o filenames th

This works as intended, for the most part. For arguments to my th function, BASH only tab-completes files ending in .tar, .tar.xz, etc. Two problems:

  1. The matching is case-sensitive. Not all tar files have lower-case extensions. (Using shopt to set nocaseglob inside the bash-completion file doesn't work.)

  2. The matching chokes on multi-word filenames, e.g. files with spaces in their names.

    [rsaw:blahb]$ ls
    bam.tgz  boom.TGZ  sad.TAR  spaces in this-file.tbz
    [rsaw:blahb]$ th<tabtab>
    bam.tgz        in             spaces         this-file.tbz  
    [rsaw:blahb]$ th spa<tabtab>
    in             spaces         this-file.tbz  
    [rsaw:blahb]$ th spaces<tabtab>   # At this point I added a backslash and pressed tab until 4 backslashes appeared
    in             spaces         this-file.tbz  
    [rsaw:blahb]$ th spaces\\\\<tabtab>   # At this point, nothing else happened 

Any help appreciated!

share|improve this question
add comment

1 Answer

You could do two things with your regex regarding the file-type extension. You could add the all-caps extensions directly to the regex, i.e. (tar|TAR) or you can add the ?i flag to make the search case-insensitive. See this for a guide: http://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive

Then, regarding the multi-word completion, here is another answer: http://stackoverflow.com/questions/1146098/properly-handling-spaces-and-quotes-in-bash-completion (I personally use _ instead of spaces in all my files for this reason)

share|improve this answer
"you can add the ?i flag to make the search case-insensitive." --> Thanks for pointing me to that. I use a lot of regular expressions in other work I do and I'd never seen that before; however, it doesn't work for bash file globbing. Thanks for the link to the other answer... We'll see if I can get some inspiration from that. –  ryran Jan 20 '13 at 17:18
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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