I have a handy little function that I use:
# A function to help with creating directory aliases and providing
# completion for them.
# Taken from here:
# http://blog.caioromao.com/2010/10/10/Custom-directory-completion.html
# Tweaked to work with more than just 'cd'
_make_dir_complete() {
local aliasname=$1
local prgname="__s_${aliasname}__"
cd "$3" >/dev/null 2>&1
local dirname=$(pwd -L)
local realpath=$(pwd -P)
cd - >/dev/null 2>&1
FUNC="function $prgname() {
local cur len wrkdir;
local IFS=\$'\\n'
wrkdir=\"$realpath\"
cur=\${COMP_WORDS[COMP_CWORD]};
len=\$((\${#wrkdir} + 2));
COMPREPLY=( \$(compgen -S/ -d \$wrkdir/\$cur| cut -b \$len-) );
}"
ALIAS="$aliasname () { $2 \"$dirname/\$*\"; }"
eval $FUNC
eval $ALIAS
complete -o nospace -F $prgname $aliasname
}
And then I have some code like this to setup my shortcuts:
test -e ~/projects &&
_make_dir_complete cdp cd ~/projects &&
_make_dir_complete pdp pushd ~/projects
This will set up two bash functions, cdp
and pdp
. cdp
I use to change directories, so I do something like cdp foo
, which will translate into cd ~/projects/foo
. pdp
works similarly, but uses pushd
instead. The nice part is that it does completion as well, so I can type cdp f
, then press TAB
, and it will complete with cdp foo
.