简体   繁体   中英

Loop through all git branches and apply commit

I have a number of branches in my repo. I want to loop thought the each branch, checkout the branch and run a command that update all packages and commit the change. In the end I want to push all.

So for I figure out how to loop thought the branch

for BRANCH in `git branch -a | grep remotes/origin/*` ;

do
    A="$(cut -d'/' -f3 <<<"$BRANCH")"
    echo $A

done 

Not sure if it is the best way of doing this. However I am still struggling how to git checkout the branch and then proceed with automatic commit.

Any ideas?

UPDATE

Based on @bk2204 answer I've done two more additional things: Figure out how to run the script withing a context of another folder https://stackoverflow.com/a/10566581/2926340 and then how to clone all remote branches automatically https://stackoverflow.com/a/40318872/2926340

That is what I came up with:

#!/bin/sh
cd my-folder #<-- tight to a specific folder
:

set -e

[ -z "$(git status --porcelain)" ] || { echo "working tree not clean" >&2; false; }

#for branch in `git branch -a | grep remotes | grep -v HEAD | grep -v master `; do
   #git branch --track ${branch#remotes/origin/} $branch #<-- throws an error if was already cloned
#done

for branch in $(git for-each-ref refs/heads/* | cut -d"$(printf '\t')" -f2 | cut -b12-)
do
    echo $branch
    # This will overwrite any changes.
    git checkout -f $branch
    # Run command here.

    rm -rf node_modules
    npm i
    # run my update thing
    git add .
    git commit -m "Update packages"
done

It is works but now it has two issues:

1) the script only runs in specific folder, so I always have to alter the path to the folder if I want to run it in a different folder
2) if I already pull all branches #git branch --track ${branch#remotes/origin/} $branch throws an error.

How would you address these issues to be able to run script on any folder and to be able to handle the case if particular remote repo was being already cloned?

git branch isn't designed to be scripted, so you're probably going to want to do something a little different. Maybe something more like this will be helpful:

#!/bin/sh

set -e

[ -z "$(git status --porcelain)" ] || { echo "working tree not clean" >&2; false; }

for branch in $(git for-each-ref refs/heads/* | cut -d"$(printf '\t')" -f2 | cut -b12-)
do
    # This will overwrite any changes.
    git checkout -f $branch
    # Run command here.
    git add .
    git commit -m "Update packages by running command"
done

Note that you can place a literal tab in the cut invocation, but I thought I'd make things a little more resistant to cut-and-paste errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM