Git 常用命令

仓库创建

创建一个目录作为工作区,并使用命令初始化为仓库

# Method 1
mkdir test          # 在当前位置新建一个文件夹,作为工作目录
cd test             # 进入到工作目录
git init            # 初始化为 Git 仓库

# Method 2
git init test01     # /新建一个目录,并将其初始化为 Git 仓库

image-20210311165248920

image-20210311165850589

克隆远程 Git 仓库到本地

从远程仓库克隆代码到本地

git clone [url]

基本配置

配置代码提交时的用户信息,名字和邮箱

# 配置提交代码时的用户信息(全局配置)
git config --global user.name "Guangran"
git config --global user.email "gr@rsecc.cn"

# 配置提交代码时的用户信息(当前仓库有效)
git config user.name "Guangran"
git config user.email "gr@rsecc.cn"

image-20210311170656295

提交代码到版本库

新建一个文件并提交到仓库

touch README.md                 # 新建一个文件
git add README.md               # 将新建的文件提交到暂存区
git commit -m "add readme"        # 提交暂存区的代码到仓库,-m 后面引号内的内容为提交说明

# 其他用法
git add [file1] [file2]                     # 提交多个文件
git add [dir]                               # 提交一个目录
git add .                                   # 提交当前目录下所有内容
git add -p                                  # 对同一个文件的多处变化,实现分次提交
git commit [file1] [file2] -m "message"       # 提交暂存区指定文件到仓库

image-20210311171002164

查看状态及修改

echo "readme" > README.md      # 在文件中写入内容
git status                      # 查看仓库当前状态 
git diff                        # 对比暂存区和工作区的差别
git log                         # 查看历史版本
git reflog                      # 查看当前分支的最近几次提交

向文件内写入内容,并查看文件状态

image-20210311174216630

比对工作区文件和暂存区文件的区别

image-20210311174238414

查看历史版本

image-20210311175108396

查看最近的提交日志

image-20210311175041907

版本回退

新建一个文件,分三次向文件内写入内容并分别提交到仓库

image-20210311175834437

查看文件的提交日志

image-20210311180225418

查看文件内容

touch test.txt                  # 创建一个新文件
#
# 第一次提交
echo "P1" >> test.txt
git add test.txt
git commit -m "p1"
# 第二次提交
echo "P2" >> test.txt
git add test.txtf
git commit -m "p2"
# 第三次提交
echo "P3" >> test.txt
git add test.txt
git commit -m "p3"
#
git log test.txt                # 查看文件的提交历史
cat test.txt                    # 查看文件内容

image-20210311181246999

回退文件到上一个版本

git reset --hard HEAD^          # 回退到上一个版本,HEAD 代表当前版本;HEAD^ 代表上一个版;HEAD^^ 代表上上个版本,以此类推
cat test.txt                    # 查看文件内容,文件已回退

image-20210311181731335

回退之后再查看一下版本库的状态,发现我们之前的一次提交不见了

git log test.txt                # 查看文件的提交历史

image-20210313093348434

还可以通过 commit ID 回退到某个版本

git reset --hard f4695      # 使用 commit ID 回退版本,需要回退到哪个版本,就是用哪个版本的 commit ID

image-20210313095822658

如果 git log 查看不到某个 commit ID 可以使用 git reflog 查看

git reflog          # 可以查看到每一次使用过的命令

image-20210313100036147

撤销修改

后面慢慢记录,有了就更新

THE END