Is it possible to make a bash alias, which would be able to prompt me for tab-completion of a set of directories?

let's say I have a number of source code controlled projects, main path of each located under ~/projs/<projname>/trunk

Now, I have created a Bash alias, which allows more convenient switching:

go-to <projname>

will attempt to cd ~/projs/<projname>/trunk regardless of where I am in file system.

Is it possible to somehow get tab completion prompt for <projname> as I write go-to[space][Tab] so I could see which projnames I have available?

(This is recent Ubuntu distro)


It is not alias job to do this, it is called programmable completion (see man bash for details). The minimal completion example for bash looks like this:

_go-to()  {
    COMPREPLY=( $(compgen -W "~/projs/proj1/trunk ~/projs/proj2/trunk" -- "${COMP_WORDS[COMP_CWORD]}") );
complete -F _go-to go-to

So first we created a function _go-to and then bind it to command named go-to.

Now go-to <tab> will get completed to go-to /home/user/projs/proj and another <tab> will list propositions:

/home/user/projs/proj1/trunk /home/user/projs/proj2/trunk
  • I think the proposed completions should be something like the output of find $HOME/projs -maxdepth 1 -type d -exec basename {} \;, or maybe even check that a subdirectory trunk exists. – Bodo Feb 21 at 11:53
  • Thank you, I found out that I could do it easier by: complete -W "$(ls -1 ~/projs/)" go-to – Gnudiff Feb 21 at 14:47
  • @Gnudiff If all your projects are in the same directory, then yes, although I would not use ls for this unless you are sure there are no whitespaces in their names. You can also first build a variable with their names under special conditions (like e.g. recently modified directory) and only then complete -W "$var" .... Above is only the minimal example to grasp an idea. – jimmij Feb 21 at 15:05

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.