Git 常用命令

145 阅读2分钟

git 常用命令


# 本地库连接远程仓库

git remote add origin [url]


# 查看远程库

git remote -v


# 取消本地库与远程库关联

git remote remove origin


# clone 远程代码

git clone [url]


# clone 远程指定分支代码

git clone -b [branch_name] [url]


# 查看状态

git status


# 本地->缓存区

git add .


# 缓存区->工作区

git commit -m '文字描述'


# 工作区->远程仓库

git push origin master


# 强行合并工作区与远程仓库代码

git pull origin master --allow-unrelated-histories


# 拉取远程分支

git pull <远程主机名> <远程分支名>:<本地分支名>

git pull origin master:master


# 查看当前详细分支信息(可看到当前分支与对应的远程追踪分支):

git branch -vv


# 查看config列表

git config --list


# 查看ssh文件夹位置

open ~/.ssh


# 合并分支

新分支merge到主分支前,先merge主分支到新分支,确保没有冲突, 不能污染主分支,如果有冲突,手动解决冲突文件。再提交到远程分支,确保新分支的修改是基于最新的主分支。


add 和 commit 确认test分支push之后没问题了再checkout到master分支,再merge

如果两人同时改了某一个分支,需要手动解决冲突。

git pull origin master # 先更新主分支再merge到其他分支 否则检测不到变化

git branch # 查看分支

git branch -a # 查看远程分支

git branch <name> # 创建分支

git checkout <name> # 切换分支

git checkout -b <name> # 创建分支并切换到该分支

git merge <name># <name>分支合并到当前分支

git push origin <远程分支名># 推送当前分支内容到远程分支

git push origin --delete <branch_name> # 删除远程分支

git branch -d <name> # 删除一个已被终止的分支

git branch -D <branch_name> # 删除一个正打开的分支

git branch --set-upstream-to=origin/test test 设置本地分支对应的远程分支,设置好后可直接 git pull 拉取代码

git log 查看后退对应版本

git reset --hard [版本号] # 撤销分支merge 回退到对应版本

git branch -vv # 查看本地分支详细信息



# 操作标签

git tag 查看当前分支下的标签

git tag <tagname> 创建标签

git tag -a v1.0.1 -m ‘1.0.1 版本’ 创建带附注标签

git push origin v1.0.1 # 将v1.0.1标签提交到git服务器

git push origin –-tags # 将本地所有标签一次性提交到git服务器

git tag -d v1.0.1 # 删除标签

git push origin :refs/tags/v1.0.1 # 删除远程标签

git fetch origin tag v1.0.1 # 拉取指定版本



# 回滚操作

git revert 删除撤销某次commit,此次操作会作为一次新的commit 提交,同时不会影响之前的commit记录


git revert HEAD 撤销前一次 commit

git revert HEAD^ 撤销前前一次 commit

git revert commit_id 撤销指定的版本