Check if pull needed in Git

后端 未结 24 1288
忘了有多久
忘了有多久 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 14:12

    If you run this script, it will test if the current branch need a git pull:

    #!/bin/bash
    
    git fetch -v --dry-run 2>&1 |
        grep -qE "\[up\s+to\s+date\]\s+$(
            git branch 2>/dev/null |
               sed -n '/^\*/s/^\* //p' |
                    sed -r 's:(\+|\*|\$):\\\1:g'
        )\s+" || {
            echo >&2 "Current branch need a 'git pull' before commit"
            exit 1
    }
    

    It's very convenient to put it as a Git hook pre-commit to avoid

    Merge branch 'foobar' of url:/path/to/git/foobar into foobar
    

    when you commit before pulling.

    To use this code as a hook, simply copy/paste the script in

    .git/hooks/pre-commit
    

    and

    chmod +x .git/hooks/pre-commit
    

提交回复
热议问题