Skip to content

Instantly share code, notes, and snippets.

@sirhc
Created January 7, 2011 21:12
Show Gist options
  • Save sirhc/770107 to your computer and use it in GitHub Desktop.
Save sirhc/770107 to your computer and use it in GitHub Desktop.
Simple function to change to a directory given a key
#!/bin/bash
#
# Bookmarks for filesystem paths. For example,
# > go add logs /var/log
# > go logs
# > pwd
# /var/log
go () {
if [[ $# -eq 0 ]]; then
echo 'Usage: go KEYWORD'
echo ' go list'
echo ' go search PATTERN'
echo ' go add KEYWORD [ PATH ]'
echo ' go remove [ KEYWORD ]'
return
fi
if [[ ! -f $HOME/.gorc ]]; then
return
fi
case "$1" in
'list')
cat $HOME/.gorc
;;
'search')
egrep "$2" $HOME/.gorc
;;
'add')
local keyword=${2:?"missing KEYWORD"}
local path=${3:-$(pwd)}
echo $keyword $path >>$HOME/.gorc
;;
'rm'|'remove')
local tmp=$( mktemp )
if [[ -z "$tmp" || ! -f "$tmp" ]]; then
return
fi
if [[ -n "$2" ]]; then
egrep -v "^$2 " $HOME/.gorc >"$tmp"
else
egrep -v " $( pwd )$" $HOME/.gorc >"$tmp"
fi
mv "$tmp" $HOME/.gorc
;;
*)
local dir=$( egrep "^$1 " $HOME/.gorc | cut -d' ' -f2 )
if [[ -n "$dir" ]]; then
echo "$dir"
cd "$dir"
else
echo "go: $1: Keyword not found" >&2
fi
;;
esac
}
# Bash completion.
_go_compgen() {
if [ -f ~/.gorc ]; then
COMPREPLY=( $( compgen -W "$( awk '{print $1}' ~/.gorc )" ${COMP_WORDS[COMP_CWORD]} ) )
else
COMPREPLY=()
fi
}
complete -F _go_compgen go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment