2

I would like to add a custom completion spec for bash's Programmable Completion that does the following: whenever the command entered is foo, I would like to do filename/directory completion for the partial token after foo, but relative to a fixed directory (say /a/b/c) rather than the current working directory.

For example, suppose /a/b/c contains the files

hello goodbye cheers directory

and /a/b/c/directory contains the files

adieu ciao

Then, typing foo go<TAB> should complete go to goodbye, and typing foo dir<TAB>ci<TAB> should complete the argument first to directory/ and then to directory/ciao, regardless of what my current working directory is.

I was hoping to be able to set this up with just a single call to complete, but after reading the manual, it doesn't appear that I can do this. Can it be done? And, if not, how could I add a compspec to do this?

5

You could use a custom completion function like the following:

_foo () { 
  local cur
  COMPREPLY=()
  cur=${COMP_WORDS[COMP_CWORD]}
  k=0
  i="/a/b/c" # the directory from where to start
  for j in $( compgen -f "$i/$cur" ); do # loop trough the possible completions
    [ -d "$j" ] && j="${j}/" || j="${j} " # if its a dir add a shlash, else a space
    COMPREPLY[k++]=${j#$i/} # remove the directory prefix from the array
  done
  return 0
}

And then register the function to be used with your command foo:

complete -o nospace -F _foo foo
  • Although I've already tested and accepted this answer (thanks, btw!), I'm still curious whether it can be confirmed that I can't achieve the functionality I'm looking for using only the many and not completely documented command-line options to complete (other than -F, that is). – lambdacalculator Dec 10 '15 at 14:02
  • @lambdacalculator You can work with -P /a/b/c, but that will always replace the completion pattern with the whole path. I don't think it's possible without a function. – chaos Dec 10 '15 at 15:15

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.