Shell – Get git branch from several folders/repos

forgitshell-script

I have a folder with several repositories inside. Is there any way I can run git branch or whatever git command inside each folder?

$ ls
project1            project2                project3            project4

And I'd like to have some kind of output like the following

$ command
project1 [master]
project2 [dev]
project3 [master]
project4 [master]

Best Answer

Try this. $1 should be the parent dir containing all of your repositories (or use "." for the current dir):

#!/bin/bash

function git_branches()
{
    if [[ -z "$1" ]]; then
        echo "Usage: $FUNCNAME <dir>" >&2
        return 1
    fi

    if [[ ! -d "$1" ]]; then
        echo "Invalid dir specified: '${1}'"
        return 1
    fi

    # Subshell so we don't end up in a different dir than where we started.
    (
        cd "$1"
        for sub in *; do
            [[ -d "${sub}/.git" ]] || continue
            echo "$sub [$(cd "$sub"; git  branch | grep '^\*' | cut -d' ' -f2)]"
        done
    )
}

You can make this its own script (but replace $FUNCNAME with $0), or keep it inside a function and use it in your scripts.

Related Question