工作中常用的git命令

对工作中经常使用的git命令进行总结。实际工作中写代码,一般情况是创建个人开发分支,再从主分支拉去代码到个人分支上,开发完毕后,提merge request,代码无误后提交到主分支。以下为常用命令:

一、克隆远程仓库到本地

git clone ${repo-address}

git clone -b ${分支名} ${仓库地址} # 使用git克隆指定分支的代码

二、拉取远程代码到本地分支

git pull ${远程主机名} ${远程分支名}:${本地分支名}

三、管理分支

1. 查看本地分支

1
2
3
git branch
* master
...

2. 查看远程分支

git branch -r

3. 查看所有分支

git branch -a

4. 创建本地的新分支

git branch ${branch-name}

5. 切换到新的分支

git checkout ${branch-name}

6. 创建+切换分支

git checkout -b ${branch-name}

7. 将新分支推送到github

git push origin ${branch-name}

8. 删除本地分支

git branch -d ${branch-name}

9. 删除远程分支

git push origin:${branch-name}

10. 切换远程分支

git checkout -b ${local-branch} origin/${remote-branch} # 作用是checkout远程的dev分支,在本地起名为dev分支,并切换到本地的dev分支

四、删除错误上传到远程仓库的文件夹

1
2
3
4
5
git clone 你的文件路径
ls -la
git rm -r --cached 要删除的文件夹
git commit -m '删除了target' # 提交,添加操作说明
git push -u origin master # 将本次更改更新到github项目上去

关于git rm -r --cached中的“cached”参数,经查阅StackOverflow,解释如下:

git rm on the other hand removes a file from the working directory and the index and when you commit, the file is removed from the tree as well. git rm –cached however removes the file from index alone and keeps it in your working copy. This is the exact opposite of git add file In this case, you made index to be different from the HEAD and the working, in it that the HEAD has the previously committed version of the file, working copy had the las modification if any or content from HEAD of the file and you removed the file from the index. A commit now will sync the index and tree and the file will be removed.