Git是一个广泛使用的分布式版本控制系统,它允许开发者高效地协作和管理代码的历史版本。以下是Git中一些最常用的操作命令。
工作中常用流程
克隆代码到本地
git clone xxx.git
拉取最新代码,先git fetch更新所有远程仓库,再用git pull从最新的仓库拉取代码
git fetch
git pull
切换分支,实际工作中经常要切换到分支进行开发
1、直接切换,但当本地有改动时无法切换,一般采用流程2
git checkout $branch_name
2、缓存本地改动再切换
git stash save "xxxx"
git stash list
git checkout $branch_name
切换回去
git checkout $raw_branch_name
释放缓存,$x是多少用git stash list查看
git stash apply stash@{$x} or git stash pop stash@{x}
push代码到远程仓库一般流程
查看当前代码改动
git status
git diff $file_path
确认改动正确后,添加改动到本地git,为了防止出错,一般逐个添加
git add $file_path
git commit -m "xxxx"
推送到默认的远程分支
git push
也可推送到指定的远程分支,如不存在,则会新建远程分支,因此常用来新建分支
git push origin $local-branch-name:$remote-branch-name
使用频次较低的命令
新建本地分支
git checkout -b $branch_name
从其他分支更新指定文件,会直接覆盖原内容
git checkout $branch_name -- file_path
从其他分支pull代码
git pull origin $remote_branch:$local_branch
删除本地分支
git branch -d $branch_name
缓存单个文件
git stash -- temp.c
缓存多个文件
git stash push a_file b_file c_file ...
查看所有分支
git branch -a
复原文件
git restore --staged filepath
撤销上次commit,但commit内容是保留在缓存中的
git reset --soft HEAD^
丢弃所有uncommit的changes
git reset --hard $版本号
查看上次git pull的时间
date -r .git/FETCH_HEAD
比较两个分支或者commit不同
git diff a b --stat
比较具体文件
git diff a b filename
查看被修改的文件列表
git diff --name-only a b
用于查看当前分支以及分支之间的关系和跟踪情况
git branch -vv
查看最近两次两次提交
git reflog -n 2
合并指定commit代码
git cherry-pick $commit_id
Git命令大全
git init
初始化一个新的Git仓库。在你的项目目录中运行此命令,会创建一个新的.git
子目录,这个目录包含所有Git的版本跟踪元数据。
git clone
克隆一个已存在的Git仓库。这个命令会创建一个与远程仓库同步的本地副本。
git clone <repository-url>
git add
将文件添加到暂存区域(staging area)。在你修改了一些文件之后,使用git add
来添加这些改动,准备进行下一次的提交。
git add <file-or-directory>
git add .
git commit
将暂存区域的改动提交到仓库。每一次提交都会记录下相关的改变,并附上一条提交信息。
git commit -m "Commit message"
git status
查看仓库当前的状态,包括哪些文件被修改了但还没有提交,哪些文件已经暂存了,等待下次提交。
git push
将本地的提交推送到远程仓库。
git push <remote-name> <branch-name>
git pull
从远程仓库拉取最新的改动,并合并到本地分支。
git pull <remote-name> <branch-name>
git fetch
从远程仓库获取最新的分支和数据,但不自动合并到本地分支。
git fetch <remote-name>
git checkout
- 切换分支:
git checkout <branch>
用于切换到另一个分支。 - 创建并切换到新分支:
git checkout -b <new-branch>
会创建一个新的分支并切换到该分支。 - 检出文件:
git checkout -- <file>
可以丢弃工作区中某个文件的修改,将其恢复到最后一次提交时的状态。
git branch
查看、创建或删除分支。
git branch # 查看分支
git branch <new-branch> # 创建分支
git branch -d <branch> # 删除分支
git merge
将指定分支的改动合并到当前分支。
git merge <branch>
git log
查看提交历史记录。
git log
git diff
查看暂存区和工作区的差异,或是查看不同提交间的差异。
git diff # 查看工作区与暂存区的差异
git diff --staged # 查看暂存区与最后一次提交的差异
git revert
创建一个新的提交,用于撤销之前的提交。这是一种安全的取消更改的方式,因为它不影响项目的历史记录。
git revert <commit-hash>
git reset
将当前分支回退到指定的状态。git reset
具有多种模式(--soft
, --mixed
, --hard
),可以根据需要重置暂存区或工作区。
git reset <commit-hash>
以上是Git最常用的一些基本操作。Git还有更多的命令和选项可以完成各种高级版本管理任务。记得在进行某些可能会影响项目历史的操作前(比如git reset
和git revert
),一定要确保理解它们的行为,以避免意外的数据丢失。