Technology Aug 28, 2026 · 1 min read

Run a git command when entering a directory

On Mastodon, Eric Meyer asked: A bash script I want: whenever I cd into a repository directory from a directory outside that repository, git branch is fed to stdout, so I can see all the local branches. Does anything like this exist? This is easily done by replacing the built-in cd command with...

DE
DEV Community
by Jochen Lillich
Run a git command when entering a directory

On Mastodon, Eric Meyer asked:

A bash script I want: whenever I cd into a repository directory from a directory outside that repository, git branch is fed to stdout, so I can see all the local branches. Does anything like this exist?

This is easily done by replacing the built-in cd command with a custom shell function. Simply add the following code to your .bashrc or .zshrc:

cd () {
  local _arg="$1"

  builtin cd "$_arg" || exit 1
  if [-d .git]; then
    echo "Branches in $(pwd):"
    git branch
  fi
}

DE
Source

This article was originally published by DEV Community and written by Jochen Lillich.

Read original article on DEV Community
Back to Discover

Reading List