Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to setup a bash completion, and have two problems

  1. For parameter one, I needed a completion for directories
  2. For parameter two, a fixed array for completion, I just don't know how to let bash make a selection, before I always used a perl script for complex ones.
    case $COMP_CWORD in
        # default completion ? how
        COMPREPLY=( "go" "unbind" )
        # I should be using a program to echo "go" and "unbind",
        # and let bash decide which one to complete , right ? 
        # that's the only two possible parameters here

complete -F _some_func some_func
share|improve this question
up vote 5 down vote accepted

Here's one way to do it: set dirnames as the default completion, and generate custom completions for the second argument.

_some_func () {
  case $COMP_CWORD in
    1) :;; # let the default take over
    2) COMPREPLY=($(compgen -W "go unbind" "${COMP_WORDS[$COMP_CWORD]}"));;
    *) COMPREPLY=("");;
complete -F _some_func -d some_func

You could also call compgen -d when $COMP_CWORD is 1, but this doesn't work well in bash because you need to escape whitespace in the output of compgen, and you can't distinguish a newline that separates two results from a newline that is contained in a completion (rare, but possible).

share|improve this answer
+1 for the tip, @Gilles :-) – Nikhil Mulley Jan 8 '12 at 17:18

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.