A Detailed Explanation of Git Pushes and Remote Synchronization

A "push" is the process of uploading a local commit to a remote repository. Through pushing, team members can share code, synchronize changes, and collaborate on development. Understanding the various options and considerations related to pushing is essential for team collaboration.

1. Basic Concepts of Push Notifications

(1) What Is a Push Notification?

A push is the process of uploading commits from a local repository to a remote repository:

100%
graph LR
    A[Local Warehouse<br/>Local Repository] -->|git push| B[Remote Repository<br/>Remote Repository]
    B --> C[Team Members<br/>Team Members]
    C -->|git pull| D[Other Local Repositories]
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#c3e6cb

(2) Prerequisites for Push Notifications

Before sending a push notification, make sure to:

(3) Direction of the Push

Pushing is a one-way operation: local → remote


2. Basic Push Operations

(1) Push to a remote branch

▶ Example: Basic Push Notification

BASH
# Push the current branch tooriginthe corresponding branch
git push

# Output:
# fatal: The current branch feature has no upstream branch.
# To push the current branch and set the remote as upstream, use
#   git push --set-upstream origin feature

# Push and configure the upstream branch
git push -u origin feature

# Or
git push --set-upstream origin feature

# Output:
# Enumerating objects: 5, done.
# Counting objects: 100% (5/5), done.
# Writing objects: 100% (3/3), 285 bytes | 285.00 KiB/s, done.
# Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
# remote: Resolving deltas: 100% (1/1), completed with 1 local object.
# remote: 
# remote: Create a pull request for 'feature' on GitHub by visiting:
# remote:      https://github.com/user/repo/pull/new/feature
# To https://github.com/user/repo.git
#  * [new branch]      feature -> feature
# Branch 'feature' set up to track remote branch 'feature' from 'origin'.

(2) Push to a specified branch

▶ Example: Pushing to a Specific Branch

BASH
# PushmainBranch toorigin
git push origin main

# Push a local branch to a remote branch with a different name
git push origin local-branch:remote-branch

# Push the current branch to the remote repositorymainBranch
git push origin HEAD:main

# Push all local branches
git push --all origin

# Output:
# To https://github.com/user/repo.git
#  * [new branch]      develop -> develop
#  * [new branch]      feature -> feature
#  * [new branch]      main -> main

(3) Post-push verification

▶ Example: Verifying Push Results

BASH
# View Remote Branches
git branch -r

# Output:
#   origin/HEAD -> origin/main
#   origin/main
#   origin/feature

# View the upstream settings for a local branch
git branch -vv

# Output:
# * main    a1b2c3d [origin/main] feat: Add Feature
#   feature d4e5f6g [origin/feature] WIP: New Features

# Check the status of the remote repository
git remote show origin

3. Push Tags

(1) Push tags to the remote repository

▶ Example: Push Tags

BASH
# Create a tag
git tag v1.0.0

# Push a Single Tag
git push origin v1.0.0

# Output:
# To https://github.com/user/repo.git
#  * [new tag]         v1.0.0 -> v1.0.0

# Push All Tags
git push --tags

# Or
git push origin --tags

# Send tags along with the push notification
git push --follow-tags

# Push only lightweight tags
git push --follow-tags origin main

(2) Delete a remote tag

▶ Example: Deleting a tag

BASH
# Delete Local Tags
git tag -d v1.0.0

# Delete Remote Tag
git push origin --delete v1.0.0

# Or userefspecGrammar
git push origin :refs/tags/v1.0.0

# Output:
# To https://github.com/user/repo.git
#  - [deleted]         v1.0.0

(3) Tag Push Strategy

100%
graph TB
    A[Create a tag] --> B{Tag Type}
    B -->|Lightweight Tags| C[No automatic push notifications]
    B -->|Footnote Label| D[Recommended Posts]
    C --> E[Manual Push]
    D --> F[git push --tags]
    
    style D fill:#d4edda
    style F fill:#c3e6cb

4. Forced Push Notifications

(1) When is a forced push required?

Force push is used to modify the commit history of a previously pushed commit:

(2) Using --force

▶ Example: Forced Push

BASH
# Modify the last commit
git commit --amend -m "Revised commit message"

# Regular push notifications will fail
git push origin main

# Output:
# ! [rejected]        main -> main (non-fast-forward)
# error: failed to push some refs to 'https://github.com/user/repo.git'

# Mandatory Push Notifications
git push --force

# Or
git push -f

# Output:
# + a1b2c3d...d4e5f6g main -> main (forced update)

▶ Example: Security-Enforced Push

BASH
# --force-with-lease Safer
# If there are new commits pushed by others on the remote repository,Will reject the push notification
git push --force-with-lease

# Output:
# + a1b2c3d...d4e5f6g main -> main (forced update)

# If there are new commits on the remote
git push --force-with-lease

# Output:
# ! [rejected]        main -> main (stale info)
# error: failed to push some refs to 'https://github.com/user/repo.git'

(4) Risks of Mandatory Push Notifications

100%
graph TB
    A[Mandatory Push Notifications] --> B{There is a new commit on the remote repository?}
    B -->|Yes| C[Overwrite Another User's Submission<br/>Data Loss]
    B -->|No| D[Security Updates]
    C --> E[Teamwork Issues]
    D --> F[Normal operation]
    
    style C fill:#f8d7da
    style D fill:#d4edda

⚠️ Important Warning:


5. Detailed Explanation of Push Options

(1) Common Push Options

Option Description Use Case
-u Set Up an Upstream Branch Push a Branch for the First Time
-f Force Push Push After Modifying History
--force-with-lease Security Mandatory Push Recommended Mandatory Push Methods
--all Push all branches Batch push
--tags Push all tags Release version
--dry-run Simulate Push Preview Push Content
--verbose Detailed Output Debug Push

▶ Example: Using the Push Option

BASH
# Simulated Push Notification(Do not push)
git push --dry-run

# Output:
# To https://github.com/user/repo.git
#  * [new branch]      feature -> feature

# Detailed Output
git push --verbose

# Push and display progress
git push --progress

# Skip the hook during a push
git push --no-verify

(2) Push Configuration

▶ Example: Configuring Push Behavior

BASH
# Set the Default Push Policy
git config --global push.default simple

# push.default options:
# nothing - Do not push,Must be explicitly specified
# current - Push the current branch to the remote branch with the same name
# upstream - Push the current branch to its upstream branch
# simple - Similarupstream,But the branch names must be the same(Default)
# matching - Push all matching branches

# Configure Automatic Upstream Setup
git config --global push.autoSetupRemote true

# Right now, directlygit pushIt will automatically configure the upstream connection.
git push

(3) Push Hooks

▶ Example: Push Hook

BASH
# pre-pushHooks are executed before a push
# .git/hooks/pre-push

#!/bin/sh
# Run tests before deployment
npm test
if [ $? -ne 0 ]; then
    echo "Tests failed, aborting push"
    exit 1
fi

# Skip Hook Push
git push --no-verify

6. Push Notification Scenarios and Best Practices

(1) Handling Rejected Push Notifications

▶ Example: Handling Push Rejections

BASH
# Push Rejected
git push origin main

# Output:
# ! [rejected]        main -> main (fetch first)
# error: failed to push some refs to 'https://github.com/user/repo.git'
# hint: Updates were rejected because the remote contains work that you do
# hint: not have locally. This is usually caused by another repository pushing
# hint: to the same ref. You may want to first integrate the remote changes
# hint: (e.g., 'git pull ...') before pushing again.

# Solution1:Pull First, Then Push
git pull --rebase origin main
git push origin main

# Solution2:Push after merging
git pull origin main
git push origin main

# Solution3:Mandatory Push Notifications(Use with caution)
git push --force-with-lease origin main

(2) Push Workflow

100%
sequenceDiagram
    participant Developer
    participant Local Warehouse
    participant Remote Repository
    
    Developer->>Local Warehouse: git add & commit
    Developer->>Remote Repository: git fetch
    Developer->>Local Warehouse: git merge/rebase
    Developer->>Remote Repository: git push
    Remote Repository->>Developer: Push successful

(3) Best Practices for Push Notifications

▶ Example: Best Practices for Push Notifications

BASH
# 1. Fetch the latest code before pushing.
git fetch origin
git rebase origin/main

# 2. Make sure your submission is complete
git status
git log origin/main..HEAD

# 3. Push to a feature branch
git push -u origin feature/user-auth

# 4. Create Pull Request (on GitHub)

# 5. Delete the remote branch after merging
git push origin --delete feature/user-auth

❓ FAQ

Q What should I do if my push notification is rejected?
A A push is usually rejected because there are new commits on the remote repository. First, use git pull or git fetch + git merge/rebase to sync the remote updates, then resolve any conflicts before pushing.
Q When is a forced push required?
A You need to perform a force push when you modify the commit history of a repository that has already been pushed, such as when using --amend to modify a commit, using rebase to rewrite the history, or squashing commits. However, use this with caution; prioritize using --force-with-lease instead.
Q What is the difference between --force and --force-with-lease?
A --force unconditionally overwrites the remote branch, which may result in the loss of others' commits. --force-with-lease checks whether there are new commits on the remote; if so, it refuses to push, making it safer.
Q How do I push a new branch?
A Use git push -u origin <branch-name> to push the new branch and set the upstream branch. After that, you can use git push to push directly.
Q What is the difference between a push tag and a push branch?
A Use git push origin <branch> to push the branch, and use git push origin <tag> or git push --tags to push all tags. Tags are not automatically pushed along with the branch.

📖 Summary


📝 Exercises

  1. Basic Exercise: Create a local repository and add a remote repository; create a commit and push it to the remote repository to experience the complete push process, including setting up an upstream branch.

  2. Advanced Exercise: Simulate a scenario where a push is rejected: Create a new commit in the remote repository, create a new commit locally, attempt to push and have it rejected, then resolve the issue using pull or rebase before pushing again.

  3. Challenge: Experience a forced push: Use --amend to modify a commit that has already been pushed, then use --force-with-lease to force the push, and understand the principles and risks of a forced push.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏