DEV Community

Jochen Lillich
Jochen Lillich

Posted on Originally published at monospacementor.com on

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
}

Enter fullscreen mode Exit fullscreen mode

UDPATE: Fixed shell syntax broken by post import. Thanks, @crdtcto!

Top comments (2)

Collapse
 
crdtcto profile image
Kane Lim

Nice and simple approach. One small issue though: if [-d .git] needs spaces around the brackets (if [ -d .git ]; then), otherwise Bash will treat it as an invalid command.

I’d also use git rev-parse --is-inside-work-tree instead of checking .git directly. That handles repos using a .git file as well as normal .git directories, and works when you cd into a subdirectory of the repo.

For a quick .bashrc convenience function, though, the overall idea is clean and useful.

Collapse
 
crdtcto profile image
Kane Lim

thx, I would like to get to know you better. Would you please contact me? t_g_@CRDT_CTO