A mildly useful bit of bash tab completion

I have a bash alias cdw to cd to the top of my subversion checkout tree. It's an easy-to-type, incredibly useful trick I picked up from the Pivia (now F5) folks when they came to work for Swan Labs (now F5).

In its original form, it was just a shell alias, something like:

alias cdw="cd ~/svn/working/dir"

Dead simple, really useful.

But it would be more useful if I could cdw directly into subdirectories too. So it became a function:

cdw() {
    cd ~/svn/working/dir
}

After a while of this, I decided I really wanted tab completion. This was a bit tricky. But I eventually got this:

CDW_DIR=~/svn/working/dir/
cdw() {
    cd $CDW_DIR/$1
}
_cdw_complete() {
    local cur 
    COMPREPLY=()
    cur=${COMP_WORDS[$COMP_CWORD]}
    COMPREPLY=($(cd $CDW_DIR; compgen -d -S / -- $cur))
    return 0
}
complete -o nospace -F _cdw_complete cdw

Soon, though, I found myself with multiple repositories, and I wanted multiple cdx> functions. So I wrote a utility function to make them.

make_cd() {
    local cd_name=$1
    local cd_dir=$2
    local complete_function_name="_${cd_name}_complete"

    eval "
	$cd_name() { 
	    cd $cd_dir/\$1 
	}

	$complete_function_name() {
	    local cur
	    COMPREPLY=()
	    cur=\${COMP_WORDS[\$COMP_CWORD]}
	    COMPREPLY=(\$(cd $cd_dir; compgen -d -S / -- $cur))
	    return 0
	}

	complete -o nospace -F $complete_function_name $cd_name
    "
}

So now I have multiple cdx commands in my .bashrc file:

make_cd cdw ~/svn/repository/interesting-stuff
make_cd cdd ~/svn/repository/cobol/doomed-project
make_cd cds ~/p4/armpit

All good clean fun.