[git] Git rolls back to the specified version:


Method 1: Use the git reset command

The command can point the HEAD pointer of the current branch to the specified commit, so as to roll back the code to the specified version.
The command has three modes: --soft, --mixed, and --hard. They differ in the degree of fallback code.

  1. --mixed(default): Roll back both the HEAD pointer and the staging area to the specified commit, but do not change the contents of the work area.
  2. --softOnly roll back the HEAD pointer to the specified commit, without changing the contents of the staging area and work area.
  3. --hardRolling back the HEAD pointer, temporary storage area, and work area to the specified submission will lose the latest code modification, so use with caution.
# 查看提交历史
git log 

# 回退到指定提交(使用 --soft 模式)
git reset --soft <commit>

# 查看状态,确认回退操作是否正确
git status

# 提交回退后的代码
git commit -m "回退到 <commit>"

# 将修改的代码推送到远程仓库
git push origin <branch>

Method 2: Use the git revert command

The git revert command can reverse the modification of the specified submission to the current branch, which is equivalent to 撤销指定提交的修改.
This method is safer than using the git reset command, because it does not change the commit history, but creates a new commit to undo the previous modification.

# 查看提交历史
git log

# 撤销指定提交,这样会创建一个新的提交来撤销之前的修改
git revert <commit>

# 提交撤销操作
git commit -m "回退到版本 <commit>"

# 推送到远程仓库
git push origin <branch>

Method 3: Use the git checkout command

The git checkout command can point the HEAD pointer of the current branch to the specified submission, and replace the content of the workspace with the content of the specified submission. this way 不改变提交历史,但会直接覆盖工作区的内容,慎用.

# 查看提交历史
git log

# 切换到指定提交
git checkout <commit>

# 提交回退后的代码
git commit -m "回退到版本 <commit>"

# 切回到原来的分支
git checkout <branch>

# 推送当前分支到远程仓库
git push origin <branch>
#<branch> 表示当前分支的名称,例如 master。这个命令会将本地分支的提交推送到远程仓库,并将远程分支更新为与本地分支一致。

Common errors and their solutions are as follows:

【1】error: failed to push some refs to '[email protected]:/.git'
原因: This error is usually caused by inconsistencies in the commit history of the local branch and the remote branch.
解决办法: First execute the git pull command to pull the code of the remote branch to the local, and then execute the git push command to push the code.

[2] error: src refspec does not match any
解决: This error is usually caused by a non-existent local branch or a typo.
解决办法: First execute the git branch command to view the local branch list, and confirm whether the branch name is correct. If it does not exist, you need to create a branch first.

【3】error: failed to push some refs to '[email protected]:/.git'
解决: This error is usually caused by insufficient permissions.
解决办法: Confirm whether the current user has the permission to push the code to the remote warehouse. If not, you need to contact the administrator for authorization.

Guess you like

Origin blog.csdn.net/weixin_53791978/article/details/132160078