Git操作场景示例

1. 删除掉本地不存在的远程分支

多人合作开发时,如果远程的分支被其他开发删除掉,在本地执行git branch --all依然会显示该远程分支,可使用下列的命令进行删除:

1
2
3
4
5
6
# 使用 pull 命令,添加 -p 参数
$ git pull -p

# 等同于下面的命令
$ git fetch -p
$ git fetch --prune origin

2.创建自己的分支

1
2
3
4
5
6
7
8
# 从develop分支导出自己的分支dev
$ git checkout -b dev-lxy
# 将本地分支提交到远程分支
$ git push origin dev-lxy:dev-lxy
# 将本地分支和远程分支绑定
$ git branch -u origin/dev-lxy
# 提交代码
$ git push

3.切换远程分支

1
2
3
4
5
6
7
8
9
10
11
12
# 添加一个远程分支
$ git remote add origin-devops http://ip/**/**.git
# 查看远程分支信息
$ git remote -v
# 更新远程分支到本地分支
$ git fetch origin-devops
# 本地分支绑定远程origin-devops/develop-lxy分支
$ git branch -u origin-devops/develop-lxy
# 查看分支状态
git branch -vv
# 切回去
$ git branch -u origin/develop-lxy

4.修改远程分支名称:origin/dev-a—>origin/dev-lxy

1
2
3
4
5
6
7
8
9
10
11
12
# 先checkout到要修改的远程分支
$ git checkout dev-a
# 创建本地分支的名称
$ git checkout -b dev-lxy
# 将本地的代码提交到远程分支(冒号右边为远程分支,不存在则会自动创建)
$ git push origin dev-lxy:dev-lxy
# 修改正在跟踪的上游分支(将当前的本地分支绑定(track)到远程分支)
$ git branch -u origin/dev-lxy
# 删除远程分支
$ git push origin :dev-a
# 最后删除本地分支
$ git branch -d dev-a

5.修改之前的提交文件(Commit Id)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 回退到之前的提交
$ git reset --hard <commit ID>
# 然后新增一个本地分支并切换到新增的分支
$ git checkout -b <新的分支名>
# 然后修改代码
# 然后提交并推送
$ git add .
$ git commit -m "desc"
$ git push origin <新的分支名>:<新的分支名>
# 这样代码就提交到远程的新分支名称了
# 然后切回到正常的开发分支
$ git checkout develop-lxy
# 回到最新的提交记录
$ git reset --hard <commit ID>
# 接下来就是愉快的继续开发了

5.当前节点打TAG

  • 1.添加标签
    1
    2
    3
    4
    5
    # 添加标签(默认对当前版本)
    $ git tag <标签名称>
    or
    # 添加带有描述信息的附注标签
    $ git tag -a <标签名称> -m "<标签描述信息>"
  • 2.提交TAG到远程分支
    1
    2
    # 将本地所有的标签全部提交到远程仓库
    $ git push <远程仓库的别名> –-tags

6.git多路径(remote)切换

1
2
3
4
5
6
7
8
9
10
11
12
# 删除本地远程git路径
git remote rm origin 
# 添加新的远程分支
git remote add origin http://<IP>:<PORT>/auth/authcenter.git 
# 切换远程仓库地址:
# 方式一:修改远程仓库地址
【git remote set-url origin URL】 更换远程仓库地址,URL为新地址。
# 方式二:先删除远程仓库地址,然后再添加
【git remote rm origin】 删除现有远程仓库 
【git remote add origin url】添加新远程仓库
# 查看远程仓库的地址
git remote -v

7.更改本地和远程分支的名称

1
2
3
git branch -m old_branch new_branch # Rename branch locally 
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote

8.删除本地和远程分支

1
2
3
4
5
6
7
8
9
10
# 1. 切换到要操作的项目文件夹 
$ cd <ProjectPath>
# 查看项目的分支们(包括本地和远程) 
$ git branch -a
# 3. 删除本地分支 
$ git branch -d <BranchName>
# 4. 删除远程分支 
$ git push origin --delete <BranchName>
# 5. 查看删除后分支们 
$ git branch -a

9.合并分支到mater

1
2
3
4
5
git checkout master
git pull origin master
git merge dev
git status
git push origin master

10.如果有些文件我不想添加到暂存区,但是不小心添加了怎么解决?

1
2
# 将文件从暂存区中删除
git rm --cached <文件名>