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]

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


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

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

    # 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)]"

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

for dir in */
  do (cd $dir && echo "$dir [$(git rev-parse --abbrev-ref HEAD)]")

It will output (almost) what you want.

project1/ [master]
project2/ [dev]
project3/ [master]
project4/ [master]
New contributor
Antoine is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • 2
    $(ls -d */) is a brittle way of saying */. – muru 2 days ago
  • I don't get it, how would you do that : 'for dir in */ ... ' ? – Antoine 2 days ago
  • Yes, exactly that: for d in */ – muru 2 days ago
  • Ok, I'm far from an expert in bash and it certainly works in other version of shell. But with my version of zsh (5.7.1 (x86_64-apple-darwin17.7.0)), it doesn't work : "zsh: no matches found: */" – Antoine 2 days ago
  • 1
    Then there are no matches. In that case, your loop would have failed as well. – muru 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.