常用的 Git 命令

115 阅读1分钟

以下是一些常用的 Git 命令及其简要说明:

基本操作

  • 初始化一个新的 Git 仓库

    git init
    
  • 克隆一个已有的 Git 仓库

    git clone <repository_url>
    
  • 查看仓库的状态

    git status
    
  • 添加文件到暂存区

    git add <file_or_directory>
    
  • 提交更改到本地仓库

    git commit -m "commit message"
    
  • 查看提交历史

    git log
    

分支管理

  • 列出所有分支

    git branch
    
  • 创建一个新分支

    git branch <branch_name>
    
  • 切换到另一个分支

    git checkout <branch_name>
    
  • 创建并切换到一个新分支

    git checkout -b <branch_name>
    
  • 合并一个分支到当前分支

    git merge <branch_name>
    
  • 删除一个本地分支

    git branch -d <branch_name>
    

远程操作

  • 查看所有远程仓库

    git remote -v
    
  • 添加一个远程仓库

    git remote add <remote_name> <repository_url>
    
  • 从远程仓库获取最新更改

    git fetch <remote_name>
    
  • 将更改推送到远程仓库

    git push <remote_name> <branch_name>
    
  • 从远程仓库拉取最新更改并合并到当前分支

    git pull <remote_name> <branch_name>
    

文件和更改管理

  • 查看文件的更改

    git diff
    
  • 查看特定文件的更改

    git diff <file>
    
  • 撤销对文件的修改(重置到上一次提交)

    git checkout -- <file>
    
  • 从暂存区撤销文件

    git reset <file>
    

历史操作

  • 查看特定提交的内容

    git show <commit_id>
    
  • 查看特定文件的历史

    git log <file>
    
  • 回退到某个历史提交

    git reset --hard <commit_id>
    

高级操作

  • 交互式 rebase

    git rebase -i <commit_id>
    
  • 删除远程分支

    git push <remote_name> --delete <branch_name>
    
  • 清理未跟踪的文件

    git clean -fd
    

这些命令涵盖了 Git 的大部分基本操作和一些常见的高级操作。根据工作流程,可能会用到不同的命令。