ARW
ARW

Reputation: 3416

Autocomplete function argument in shell function

Have a couple quick bash functions that let me get to folders I use often:

function dp() {
    cd ~/Development/Personal/$1
}

function dw() {
    cd ~/Development/Work/$1
}

So I can type dp some-project to go directly to a personal project for example. It would be killer if I could get tab-completion working on the function argument so it automatically pulled in filenames from the directory I'm going to navigate to, but I can't seem to figure it out...

Ideally I could just type dp b{tab} and get dp blog for example, where blog is a folder in the ~/Development/Personal/ directory.

Anyone know how to make this work? I'm using ZSH if it matters!

Upvotes: 5

Views: 663

Answers (1)

Sir Athos
Sir Athos

Reputation: 9867

It does matter very much which shell you're using.

First, let me mention that you can add often used directories to a "hotlist" that you can then use with cd. For instance, you could do this:

cdpath=(~/Development/Personal ~/Development/Work)

and then, at any point (and from any directory), you should be able to type cd blog. Tab completion will work as well.

If you still want to have your own functions for cd and add tab completion for them, here's a very informative article about how to write your own completion functions.

In a nutshell, you create a file in the zsh completion directory, called _dp, and add something like this to it:

#compdef dp

compadd $(command ls -1 $HOME/Development/Personal 2>/dev/null --color=none | sed -e 's/ /\\ /g')

Upvotes: 5

Related Questions