1

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)

1 Answer 1

2

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
3
  • 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
    Commented Feb 21, 2019 at 11:53
  • Thank you, I found out that I could do it easier by: complete -W "$(ls -1 ~/projs/)" go-to
    – Gnudiff
    Commented Feb 21, 2019 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
    Commented Feb 21, 2019 at 15:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .