Harrison Xi
Harrison Xi

Reputation: 796

How to get the latest code of a branch?

I want to write a bash to do an auto building. But I just know how to checkout a branch and pull the latest code manually. I want to use a bash to switch to or checkout (if it's needed) a branch and then pull the latest code.

My problem:

  1. How to check if the branch is existing on local?
  2. How to check if we have changes on local?

Or is there a faster way to finish the update?

====

For the question 1, looks like that I can use git checkout directly.

For the question 2, how to know if a git command gets an error?

Upvotes: 0

Views: 686

Answers (3)

Ian2thedv
Ian2thedv

Reputation: 2701

Seeing as you would deal with conflicts manually, I would do the following:

  1. Check if there are any local changes. If there are use git stash to save the all changes/untracked files, otherwise continue.
  2. Checkout the branch
  3. If there was local changes, use stash apply to apply the local changes.
  4. If the stash apply resulted in conflicts, use git stash --reverse to undo the apply and exit with some error indicating that a manual merge is required.
  5. ** your build logic **

All of this can be done with something like:

if [ -z "$(git status --porcelain)"]; then
    git checkout remote/branch
else
    git stash
    git checkout remote/branch
    git stash apply

    #Check if there are any unmerged files, if there is, exit with error
    if [ ! -z "$(git ls-files -u) "]; then
        echo "Error: there seems to be some conflicts"
        exit 1
    fi
fi

** your build logic **

Upvotes: 2

ElpieKay
ElpieKay

Reputation: 30956

If it's only for auto building, git fetch <remote> <branch> && git checkout -f FETCH_HEAD is enough. This cmd always gets the latest commit of the <branch> from the remote server as long as you are sure the <remote> and <branch> names are correct. In bash after a git cmd, a following "echo $?" can give the exit status of the git cmd. Generally if it's 0, the git cmd has no error. If non 0, it indicates an error. You could see the details in git <cmd> --help, some of which may describe the exit status.

Upvotes: 1

f7o
f7o

Reputation: 663

See

man git-log

You could write some script watching for new commits on specific branch after fetching changes

git log -n 1 origin/master

Upvotes: 0

Related Questions