Check if pull needed in Git

后端 未结 24 1654
忘了有多久
忘了有多久 2020-11-22 13:34

How do I check whether the remote repository has changed and I need to pull?

Now I use this simple script:

git pull --dry-run | grep -q -v \'Already          


        
24条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 13:57

    After reading many answers and multiple posts, and spending half a day trying various permutations, this is what I have come up with.

    If you are on Windows, you may run this script in Windows using Git Bash provided by Git for Windows (installation or portable).

    This script requires arguments

    - local path e.g. /d/source/project1
    - Git URL e.g. https://username@bitbucket.org/username/project1.git
    - password
    
    if a password should not be entered on the command line in plain text,
    then modify the script to check if GITPASS is empty; do not
    replace and let Git prompt for a password
    

    The script will

    - Find the current branch
    - Get the SHA1 of the remote on that branch
    - Get the SHA1 of the local on that branch
    - Compare them.
    

    If there is a change as printed by the script, then you may proceed to fetch or pull. The script may not be efficient, but it gets the job done for me.

    Update - 2015-10-30: stderr to dev null to prevent printing the URL with the password to the console.

    #!/bin/bash
    
    # Shell script to check if a Git pull is required.
    
    LOCALPATH=$1
    GITURL=$2
    GITPASS=$3
    
    cd $LOCALPATH
    BRANCH="$(git rev-parse --abbrev-ref HEAD)"
    
    echo
    echo git url = $GITURL
    echo branch = $BRANCH
    
    # Bash replace - replace @ with :password@ in the GIT URL
    GITURL2="${GITURL/@/:$GITPASS@}"
    FOO="$(git ls-remote $GITURL2 -h $BRANCH 2> /dev/null)"
    if [ "$?" != "0" ]; then
      echo cannot get remote status
      exit 2
    fi
    FOO_ARRAY=($FOO)
    BAR=${FOO_ARRAY[0]}
    echo [$BAR]
    
    LOCALBAR="$(git rev-parse HEAD)"
    echo [$LOCALBAR]
    echo
    
    if [ "$BAR" == "$LOCALBAR" ]; then
      #read -t10 -n1 -r -p 'Press any key in the next ten seconds...' key
      echo No changes
      exit 0
    else
      #read -t10 -n1 -r -p 'Press any key in the next ten seconds...' key
      #echo pressed $key
      echo There are changes between local and remote repositories.
      exit 1
    fi
    

提交回复
热议问题