Skip to content

Git 命令

基础操作

  1. 初始化仓库。
sh
$ git init
$ git init
  1. 添加文件到暂存区
sh
$ git add .
$ git add .
  1. 将暂存区内容添加到仓库中
sh
$ git commit -m [message]
# `-a` 参数设置修改文件后不需要执行 `git add` 命令,直接来提交
$ git commit -am [message]
$ git commit -m [message]
# `-a` 参数设置修改文件后不需要执行 `git add` 命令,直接来提交
$ git commit -am [message]

设置提交代码时的用户信息

sh
$ git config --global user.name 'yang'
$ git config --global user.email '30896355@qq.com'
$ git config --global user.name 'yang'
$ git config --global user.email '30896355@qq.com'

获取文件状态

sh
$ git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README
    new file:   hello.ts
$ git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   README
    new file:   hello.ts

通常我们使用 -s 参数来获得简短的输出结果

sh
$ git status -s
AM README
A  hello.ts
$ git status -s
AM README
A  hello.ts

修改操作

回退版本

sh
$ git reset HEAD^            # 回退所有内容到上一个版本
$ git reset HEAD^ hello.ts   # 回退 hello.ts 文件的版本到上一个版本
$ git reset  052e            # 回退到指定版本
$ git reset HEAD^            # 回退所有内容到上一个版本
$ git reset HEAD^ hello.ts   # 回退 hello.ts 文件的版本到上一个版本
$ git reset  052e            # 回退到指定版本

将文件从暂存区和工作区中删除

sh
$ git rm <file>
$ git rm <file>

移动或重命名工作区文件。

sh
$ git mv [file] [newfile]
$ git mv [file] [newfile]

远程操作

添加远程仓库

sh
$ git remote add origin https://github.com/xxxxx/test.git
$ git remote add origin https://github.com/xxxxx/test.git

发布本地代码到远程分支

常见错误 解决方法

remote: [session-bd4fcd83] Access denied

sh
$ git push -u origin master
$ git push -u origin master

同步远程分支

sh
$ git remote update yang-blog --prune
$ git remote update yang-blog --prune

下载远程代码并合并

sh
$ git pull
$ git pull

上传远程代码并合并

sh
$ git push
$ git push

合并分支

sh
$ git merge [branch]
$ git merge [branch]

覆盖线上分支

sh
$ git push -u origin master -f
$ git push -u origin master -f

删除远程文件,保留本地文件

sh
$ git rm -r --cached <file>
$ git commit -m 'delete file'
$ git push
$ git rm -r --cached <file>
$ git commit -m 'delete file'
$ git push

设置本地git环境识别大小写

sh
$ git config core.ignorecase false
$ git config core.ignorecase false

分支管理

分支增删改查

切换分支

sh
$ git checkout -b <name> # 新分支名称
$ git checkout -b <name> # 新分支名称

操作分支

sh
$ git branch -d <name> # 删除分支
$ git branch -c <name> # 复制分支
$ git branch -m oldName newName #修改分支名
$ git branch -d <name> # 删除分支
$ git branch -c <name> # 复制分支
$ git branch -m oldName newName #修改分支名

常见问题

清楚上一个登录账号的信息
sh
$ git config --system --unset credential.helper
$ git config --system --unset credential.helper