/ git-update
git-update
 1  #!/bin/bash
 2  
 3  set -e # bail on errors
 4  
 5  function current_branch() {
 6    git rev-parse --abbrev-ref HEAD | sed -e 's/^heads\///'
 7  }
 8  
 9  ORIG_BRANCH=$(current_branch)
10  DEFAULT_REMOTE=$(git config --get branch.${ORIG_BRANCH}.remote)
11  REMOTE="${1:-$DEFAULT_REMOTE}"
12  if [[ "$ORIG_BRANCH" = "HEAD" ]]; then
13    echo "Cannot update in a detached HEAD state"
14    exit 1
15  fi
16  if [[ -z "$2" ]]; then
17    BRANCHES="$ORIG_BRANCH"
18  else
19    if [[ "$1" = "$REMOTE" ]]; then
20      shift
21    fi
22    BRANCHES="$@"
23  fi
24  
25  STASH_OUTPUT=$(git stash)
26  if [[ "$STASH_OUTPUT" = "No local changes to save" ]]; then
27      POP_STASH=0
28  else
29      POP_STASH=1
30  fi
31  
32  git fetch --prune --tags "$REMOTE"
33  
34  for BRANCH in $BRANCHES; do
35    echo "* Updating $BRANCH from $REMOTE/$BRANCH"
36    if [[ "$BRANCH" != "$(current_branch)" ]]; then
37      git checkout "$BRANCH"
38    fi
39    git rebase "$REMOTE/$BRANCH"
40  done
41  
42  if [[ "$ORIG_BRANCH" != "$(current_branch)" ]]; then
43    git checkout "$ORIG_BRANCH"
44  fi
45  
46  if [[ $POP_STASH -eq 1 ]]; then
47    git stash pop
48  fi