Skip to content

Instantly share code, notes, and snippets.

@mathyourlife
Last active December 30, 2015 08:59
Show Gist options
  • Save mathyourlife/7806290 to your computer and use it in GitHub Desktop.
Save mathyourlife/7806290 to your computer and use it in GitHub Desktop.
cdr function: cd up to a "root" directiory
# Add this function to your ~/.bashrc file to allow you to jump to the top of a complex dir tree
#
# Examples:
# user@host:~/git_stuff/git_repo1/dir1/subdir/subsubdir $ cdr
# user@host:~/git_stuff/git_repo1 $
#
# user@host:~/svn_stuff/svn_repo1/dir1/subdir/subsubdir $ cdr
# user@host:~/svn_stuff/svn_repo1 $
#
# user@host:~/just/a/normal/dir/structure $ cdr
# user@host:~ $
#
# user@host:/var/log/apache $ cdr
# user@host:/ $
# Snippet of bashrc https://github.com/MathYourLife/dotfiles/blob/master/bash/bashrc
# Walk backwards until you hit a "root" folder
function cdr() {
# for git repos we can make 1 jump
git_root=`git rev-parse --show-toplevel 2> /dev/null`
if [ "$git_root" != "" ]
then
cd $git_root
return 0
fi
while [ 1 ]
do
# Stop at the true root
if [ "$(pwd)" == "/" ]; then
break
fi
# Stop at the home dir
# You should have just used cd with no arg :)
if [ "$(pwd)" == "/home/$USER" ]; then
break
fi
# for subversion < 1.7 thanks to https://gist.github.com/egon1024
# If this directory contains a .svn directory, but our parent does not,
# we're at the top of a source tree and we'll call this a "root"
if [ -d "./.svn" -a ! -d "$(dirname $(pwd))/.svn" ]; then
return 0
fi
if [ $FOUND_ROOT -ne 1 ]
then
ROOT_TYPES=("^.svn$")
for root_type in "${ROOT_TYPES[@]}"
do
IS_ROOT=$(ls -a | grep -cP '^.git$')
if [ "$IS_ROOT" == "1" ]
then
return 0
fi
done
fi
cd ..
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment