插件窝 干货文章 linux如何安装git及git常用命令

linux如何安装git及git常用命令

Git bash 分支 name 305    来源:    2025-04-21

Linux 下 Git 安装与常用命令指南

Git 安装方法

基于 Debian/Ubuntu 的系统

sudo apt update
sudo apt install git

基于 RHEL/CentOS/Fedora 的系统

# RHEL/CentOS 7/8
sudo yum install git

# Fedora 或较新的 RHEL/CentOS
sudo dnf install git

基于 Arch Linux 的系统

sudo pacman -S git

安装后验证

git --version

Git 配置

安装完成后,建议设置全局用户信息:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Git 常用命令

基础命令

  1. 初始化仓库

    git init
    
  2. 克隆仓库

    git clone <repository-url>
    
  3. 查看状态

    git status
    
  4. 添加文件到暂存区

    git add <file>       # 添加特定文件
    git add .            # 添加所有更改
    
  5. 提交更改

    git commit -m "提交信息"
    

分支管理

  1. 查看分支

    git branch           # 查看本地分支
    git branch -a        # 查看所有分支(包括远程)
    
  2. 创建分支

    git branch <branch-name>
    
  3. 切换分支

    git checkout <branch-name>
    
  4. 创建并切换分支

    git checkout -b <branch-name>
    
  5. 合并分支

    git merge <branch-name>
    
  6. 删除分支

    git branch -d <branch-name>      # 删除已合并的分支
    git branch -D <branch-name>      # 强制删除未合并的分支
    

远程操作

  1. 添加远程仓库

    git remote add <remote-name> <repository-url>
    
  2. 查看远程仓库

    git remote -v
    
  3. 推送更改

    git push <remote-name> <branch-name>
    
  4. 拉取更新

    git pull <remote-name> <branch-name>
    
  5. 获取远程更新(不自动合并)

    git fetch
    

撤销与回退

  1. 撤销工作区修改

    git checkout -- <file>
    
  2. 撤销暂存区修改

    git reset HEAD <file>
    
  3. 回退到某个提交

    git reset --hard <commit-id>
    
  4. 修改最后一次提交

    git commit --amend
    

日志与比较

  1. 查看提交历史

    git log
    git log --oneline    # 简洁格式
    git log --graph      # 图形化显示
    
  2. 比较差异

    git diff             # 工作区与暂存区差异
    git diff --cached    # 暂存区与最新提交差异
    git diff HEAD        # 工作区与最新提交差异
    
  3. 查看某次提交的修改内容

    git show <commit-id>
    

标签管理

  1. 创建标签

    git tag <tag-name>          # 轻量标签
    git tag -a <tag-name> -m "标签信息"  # 附注标签
    
  2. 查看标签

    git tag
    
  3. 推送标签到远程

    git push <remote-name> <tag-name>    # 推送单个标签
    git push <remote-name> --tags         # 推送所有标签
    

高级用法

  1. 储藏更改

    git stash           # 储藏当前更改
    git stash list      # 查看储藏列表
    git stash apply     # 恢复最近的储藏
    git stash pop       # 恢复并删除最近的储藏
    
  2. 子模块管理

    git submodule add <repository-url> <path>
    git submodule update --init --recursive
    
  3. 重写历史

    git rebase -i <commit-id>  # 交互式变基
    
  4. 二分查找问题提交

    git bisect start
    git bisect bad      # 标记当前为有问题
    git bisect good <commit-id>  # 标记已知好的提交
    

以上是 Git 在 Linux 系统下的安装方法和常用命令,掌握这些命令可以满足日常开发中的大部分需求。