Skip to content

Instantly share code, notes, and snippets.

@marbu
Created October 27, 2014 00:47
Show Gist options
  • Save marbu/034a654e59e44395ec5a to your computer and use it in GitHub Desktop.
Save marbu/034a654e59e44395ec5a to your computer and use it in GitHub Desktop.
git-cd
# git-cd needs to be a shell function to be able to change directory
# on the other hand this means that it can't be invoked by 'git cd' command
git-cd()
{
# try to get root directory of git repo, exit if no repo found
if ! GIT_ROOT=$(git rev-parse --show-toplevel); then
return 1
fi
if [[ $# = 0 ]]; then
# no arguments, cd right into the repo root
cd ${GIT_ROOT}
elif [[ "$1" = - ]]; then
cd -
else
# otherwise cd wrt repo root
cd "${GIT_ROOT}/$1"
fi
}
# bash autocompletion for git-cd
_git-cd()
{
if ! GIT_ROOT=$(git rev-parse --show-toplevel); then
return 1
fi
# current word to complete
local CUR=${COMP_WORDS[COMP_CWORD]}
# remove absolute paths
if [[ "$CUR" =~ ^/ ]]; then
CUR=${CUR#"/"}
fi
COMPREPLY=($(cd $GIT_ROOT; compgen -S '/' -d $CUR))
}
complete -o nospace -F _git-cd git-cd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment