Skip to content

Instantly share code, notes, and snippets.

@skipcloud
Created February 5, 2020 08:15
Show Gist options
  • Select an option

  • Save skipcloud/363c5d34b54d96ce5df171ed20ace76e to your computer and use it in GitHub Desktop.

Select an option

Save skipcloud/363c5d34b54d96ce5df171ed20ace76e to your computer and use it in GitHub Desktop.
Small bash function to cd back to the top level of your git projects

Have you ever been digging around in the bowels of a repo on the command line

app
├── spec
│   ├── base_application_spec.rb
│   ├── call_center
│   │   ├── consumer
│   │   │   ├── application_spec.rb
│   │   │   ├── areas
│   │   │   │   ├── account_spec.rb                           <---- you are here
│   │   │   │   ├── addresses_spec.rb
│   │   │   │   ├── admin_spec.rb
│   │   │   │   ├── bank_issuers_spec.rb
│   │   │   │   ├── basket_spec.rb
│   │   │   │   ├── brands_spec.rb
....

Yet you are finished and need to go back to the root of the project and end up typing this ../../../../../.., mainly just guessing how many .. you need, usually you don't get it right first time. Sure would be lovely to have a command to just get you back to where you want to go...

Well, I saw a tweet recently where someone created a small alias to get them back to the root, I took it one step further and created a small bash function that does the same but won't error if you accidentally use it outside of a git project. Whack this in your .bashrc or .zshrc or wherever you keep your aliases. Now all you need to do is use the command cdr to go back to the top level of your git project.

cdr() {
  local dir=$(git rev-parse --show-toplevel 2> /dev/null)
  if [ -z "$dir" ]; then
    echo "top level git directory not found"
    return 1
  fi
  cd $dir
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment