sudo apt update
sudo apt install git
# RHEL/CentOS 7/8
sudo yum install git
# Fedora 或较新的 RHEL/CentOS
sudo dnf install git
sudo pacman -S git
git --version
安装完成后,建议设置全局用户信息:
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
初始化仓库
git init
克隆仓库
git clone <repository-url>
查看状态
git status
添加文件到暂存区
git add <file> # 添加特定文件
git add . # 添加所有更改
提交更改
git commit -m "提交信息"
查看分支
git branch # 查看本地分支
git branch -a # 查看所有分支(包括远程)
创建分支
git branch <branch-name>
切换分支
git checkout <branch-name>
创建并切换分支
git checkout -b <branch-name>
合并分支
git merge <branch-name>
删除分支
git branch -d <branch-name> # 删除已合并的分支
git branch -D <branch-name> # 强制删除未合并的分支
添加远程仓库
git remote add <remote-name> <repository-url>
查看远程仓库
git remote -v
推送更改
git push <remote-name> <branch-name>
拉取更新
git pull <remote-name> <branch-name>
获取远程更新(不自动合并)
git fetch
撤销工作区修改
git checkout -- <file>
撤销暂存区修改
git reset HEAD <file>
回退到某个提交
git reset --hard <commit-id>
修改最后一次提交
git commit --amend
查看提交历史
git log
git log --oneline # 简洁格式
git log --graph # 图形化显示
比较差异
git diff # 工作区与暂存区差异
git diff --cached # 暂存区与最新提交差异
git diff HEAD # 工作区与最新提交差异
查看某次提交的修改内容
git show <commit-id>
创建标签
git tag <tag-name> # 轻量标签
git tag -a <tag-name> -m "标签信息" # 附注标签
查看标签
git tag
推送标签到远程
git push <remote-name> <tag-name> # 推送单个标签
git push <remote-name> --tags # 推送所有标签
储藏更改
git stash # 储藏当前更改
git stash list # 查看储藏列表
git stash apply # 恢复最近的储藏
git stash pop # 恢复并删除最近的储藏
子模块管理
git submodule add <repository-url> <path>
git submodule update --init --recursive
重写历史
git rebase -i <commit-id> # 交互式变基
二分查找问题提交
git bisect start
git bisect bad # 标记当前为有问题
git bisect good <commit-id> # 标记已知好的提交
以上是 Git 在 Linux 系统下的安装方法和常用命令,掌握这些命令可以满足日常开发中的大部分需求。