git branch 、 git tag、等常用的增删改查 (本地和远程)

发布于:2024-05-18 ⋅ 阅读:(324) ⋅ 点赞:(0)

git branch 、 git tag、等常用的增删改查 (本地和远程)

分支 branch

本地分支及远程分支的增删改查

增加

  • 创建本地新分支:
    git branch <branch-name>
  • 切换到本地指定分支:
    git checkout <branch-name>
  • 创建并切换到本地新分支:
    git checkout -b <branch-name>
  • 推送本地分支到远程:
    git push origin <branch-name>

删除

  • 删除分支:
    git branch -d <branch-name> # 安全删除,只有当分支已经合并到其它分支时才会删除
    git branch -D <branch-name> # 强制删除,不论分支是否合并都会被删除
  • 删除远程分支:
    git push origin --delete <branch-name>

当我删除与标签同名的分支时出现错误,如果你尝试删除与 tag 同名的分支,你可能会收到错误消息。你将看到类似于 branch-or-tag-name matches more than one 的错误。

    git push origin :refs/heads/branch-name #如果你想指定删除分支而不是 tag,请尝试以下命令:
    git push origin :refs/tags/tag-name #如果你想指定删除 tag 而不是分支,请使用以下命令:

修改

  • 重命名分支:
    git branch -m <old-branch-name> <new-branch-name> # 修改当前分支的名称
    git branch -M <old-branch-name> <new-branch-name> # 修改其他分支的名称,如果当前处于要重命名的分支上,使用-M可以避免错误
  • 重命名远程分支
    git push origin:<old-branch-name> <new-branch-name> # 删除远程旧分支,并推送新分支

查询

  • 查看分支:
    git branch
    git branch -a #命令查看所有分支(包括本地和远程分支)的列表
  • 查看远程分支:
    git branch -r

标签 tag

本地标签及远程标签的增删改查

增加

  • 创建本地 tag:
    git tag <tagname> # 新增不带标注的tag,tag指向当前HEAD
    git tag -a <tagname> -m "your message" #创建带有注释的标签
  • 推送 tag 到远程:
    git push origin <tagname>
    git push --tags #推送所有标签

删除

  • 删除本地 tag:
    git tag -d <tagname>
  • 删除远程 tag:
    git push --delete origin <tagname>
    git push origin :refs/tags/<tagname> #删除远程tag版本

查询

  • 查询本地 tag:
    git tag
  • 查询远程 tag:
    git ls-remote --tags
  • 远程拉取所有 tags:
    git fetch origin --tags

远程仓库 remote

远程仓库的操作

  • 查看远程库的详细信息:
    git remote -v
  • 添加远程库:
    git remote add origin [url]
  • 删除远程库:
    git remote remove origin
  • 从远程库拉取代码并合并到本地:
    git pull origin <branch-name>

其它常用操作

  • 合并某分支到当前分支:
    git merge <branch-name>
  • 提交不校验团队的规则:
    git commit --no-verify -m "message"
  • 撤销工作目录中的修改(未暂存):
   git checkout -- <file>
  • 撤销暂存区的修改(已暂存但未提交):
    git reset HEAD <file>
    git checkout -- <file>
  • 回退到上一次提交的状态(丢弃最近的提交):
    git reset --hard HEAD^
  • 回退到特定的提交(丢弃这个提交之后的所有更改):
    git reset --hard <commit_hash>
  • 撤销之前 push 到远程仓库的提交:
    git revert <commit_hash>
  • 或者如果需要修改已经 push 的提交:
    git commit --amend
    git push origin <branch_name> --force

注意:使用 git reset --hard 和 git push --force 时要谨慎,因为这些操作会重写历史并可能影响其他协作者