Git基础学习记录文档

102 阅读2分钟

Git基础

1. 安装Git

  • 在Windows上,可以下载安装程序:Git for Windows
  • 在macOS上,可以使用Homebrew:brew install git
  • 在Linux上,可以使用包管理器,例如在Ubuntu上:sudo apt-get install git

2. 配置Git

  • 设置全局用户名:git config --global user.name "Your Name"
  • 设置全局邮箱:git config --global user.email "youremail@example.com"
  • 查看配置信息:git config --list

3. 创建新仓库

  • 在当前目录初始化新仓库:git init

4. 克隆远程仓库

  • 克隆远程仓库到本地:git clone [url]

文件操作

1. 查看文件状态

  • 查看当前目录文件状态:git status

2. 添加文件到暂存区

  • 添加单个文件:git add [file]
  • 添加多个文件:git add [file1] [file2]
  • 添加所有修改过的文件:git add .

3. 提交更改

  • 提交暂存区文件到本地仓库:git commit -m "commit message"

4. 查看提交历史

  • 查看提交历史:git log
  • 查看简化的提交历史:git log --oneline

5. 回退到某个版本

  • 回退到上一个版本:git reset --hard HEAD^
  • 回退到指定版本:git reset --hard [commit_id]

分支操作

1. 创建分支

  • 创建新分支:git branch [branch_name]
  • 创建并切换到新分支:git checkout -b [branch_name]

2. 切换分支

  • 切换到已有分支:git checkout [branch_name]

3. 查看所有分支

  • 查看本地分支:git branch
  • 查看远程分支:git branch -r
  • 查看所有分支:git branch -a

4. 合并分支

  • 将其他分支合并到当前分支:git merge [branch_name]

5. 删除分支

  • 删除本地分支:git branch -d [branch_name]
  • 删除远程分支:git push origin --delete [branch_name]

远程仓库操作

1. 添加远程仓库

  • 添加远程仓库:git remote add [remote_name] [url]

2. 推送到远程仓库

  • 推送本地分支到远程仓库:git push [remote_name] [branch_name]
  • 推送所有分支到远程仓库:git push --all

3. 从远程仓库拉取

  • 拉取远程仓库的更新:git pull [remote_name] [branch_name]

4. 查看远程仓库信息

  • 查看远程仓库信息:git remote -v

5. 远程仓库别名

  • 设置默认远程仓库:git remote set-head [remote_name] --auto

撤销操作

1. 撤销工作目录的更改

  • 撤销未暂存的更改:git checkout -- [file]

2. 撤销暂存区的更改

  • 撤销暂存区的更改:git reset HEAD [file]

3. 撤销最近的一次提交

  • 撤销最近的一次提交:git revert [commit_id]

其他常用命令

1. 查看文件差异

  • 查看工作目录与暂存区的差异:git diff
  • 查看暂存区与上一次提交的差异:git diff --cached [file]
  • 查看工作目录与上一次提交的差异:git diff HEAD

2. 忽略文件

  • 创建.gitignore文件,列出要忽略的文件或文件夹

3. 清理无用文件

  • 清理未跟踪的文件:git clean -f

4. 撤销合并

  • 撤销最近的一次合并:git merge --abort

这份文档涵盖了Git的基本操作,对于初学者来说,应该足够入门。