Bash function for ‘cd’ aliases
Posted by kungfucraig on Sunday, June 21, 2009
For about two weeks there I thought I was going to drop Cygwin for Windows Power Shell. As I was in the process of doing that I ran across an interesting WPSH function by Peter Provost. Nothing earth shattering, but it was pretty useful. Keep a map of aliases to full paths and provide a function “go” that changes your current directory to the full path when you invoke “go” with the appropriate alias.
I got used to using this in WPSH and decided that I would implement it in bash. Of note: I had a number of aliases and shell functions defined before that did this, but using the map, or in the case of bash a file, to hold the aliases makes the whole scheme a heck of a lot more extensible.
Anyway here it is:
##############################################
# GO
#
# Inspired by some Windows Power Shell code
# from Peter Provost (peterprovost.org)
#
# Here are some examples entries:
# work:${WORK_DIR}
# source:${SOURCE_DIR}
# dev:/c/dev
# object:${USER_OBJECT_DIR}
# debug:${USER_OBJECT_DIR}/debug
###############################################
export GO_FILE=~/.go_locations
function go
{
if [ -z "$GO_FILE" ]
then
echo "The variable GO_FILE is not set."
return
fi
if [ ! -e "$GO_FILE" ]
then
echo "The 'go file': '$GO_FILE' does not exist."
return
fi
dest=""
oldIFS=${IFS}
IFS=$'\n'
for entry in `cat ${GO_FILE}`
do
if [ "$1" = ${entry%%:*} ]
then
#echo $entry
dest=${entry##*:}
break
fi
done
if [ -n "$dest" ]
then
# Expand variables in the go file.
#echo $dest
cd `eval echo $dest`
else
echo "Invalid location, valid locations are:"
cat $GO_FILE
fi
export IFS=${oldIFS}
}



