文章

Git常用操作

1. 安装和配置

1.1 下载安装

官网下载地址

  • Windows

  • Linux

# Ubuntu/Debian
sudo apt-get install git

1.2 配置

# 配置用户名
git config --global user.name "用户名"
# 配置邮箱
git config --global user.email "邮箱"
# 添加远程仓库。origin为自己定义的远程仓库名
git remote add origin 仓库地址

2. 常用命令

2.1 查看所有分支

git branch

2.2 查看工作区状态

git status

2.3 查看commit记录

# 查看commit记录(按q退出)
git log
git show

3. 常用操作

branch_name:分支名称
remote_branch:远程分支名称

3.1 创建本地分支(默认master分支)

# 只创建分支
git branch branch_name

# 创建并切换到分支
git checkout -b branch_name

# 创建与远程分支关联的分支
git checkout -b branch_name origin/remote_branch

3.2 提交更改的文件

# 添加所有文件
git add .

# 提交
git commit -m "说明"

3.3 同步其他分支的commit到此分支

# 同步全部commit
git merge branch_name
# 同步指定的commit
git cherry-pick commit_id

3.4 修改commit注释

# 此时会进入默认vim编辑器,修改注释完毕后保存就好了。
git commit --amend

3.5 撤回commit

# ~1 代表最近的一次,~2是最近的两次,以此类推
# 撤消commit,不删除工作空间的代码,不撤销add操作
git reset --soft HEAD~1
git reset --soft HEAD^

# 不删除工作空间改动代码,撤销commit,并且撤销add操作
# 这个为默认参数,和 git reset HEAD^ 效果是一样的。
git reset --mixed HEAD~1
git reset HEAD^

# 删除工作空间改动代码,撤销commit,撤销add操作
# 注意完成这个操作后,就恢复到了上一次的commit状态。
git reset --hard HEAD~1

3.6 推送本地分支到远程分支

# 在远程仓库会自动创建一个名为branch_name的分支,并推送到此分支
git push origin branch_name

# 在远程仓库会自动创建一个名为remote_branch的分支,并推送到此分支
git push origin remote_branch:branch_name

3.7 本地分支关联远程分支

git push --set-upstream origin remote_branch

3.8 查看分支关联情况

git branch -vv

3.9 删除分支

# 删除本地分支
git branch -d branch_name

# 删除远程分支(不加本地分支时进行提交即删除远程分支)
git push origin :remote_branch
git push --delete origin remote_branch

3.10 重命名分支

git branch -m branch_name new_branch_name

3.11 进度操作(stash)

# 保存当前进度
git stash create "说明信息"
git stash   # 说明信息为最后一次提交的说明信息

# 查看所有保存的进度
git stash list

# 恢复进度
git stash apply stash@{id}
git stash apply  # 默认为最后一条

# 丢弃进度
git stash drop stash@{id}
git stash drop  # 默认为最后一条

# 查看进度
git show stash{id}

4. 其他

4.1 日志中文显示乱码(git log)

增加环境变量 LESSCHARSET=utf-8

git config --global core.quotepath false
git config --global gui.encoding utf-8
git config --global i18n.commit.encoding utf-8
git config --global i18n.logoutputencoding utf-8

5. 参考文章

许可协议:  CC BY 4.0