Git 命令-常用、分支、远程仓库、免密登录
Git 常用命令
- git config --global user.name 用户名 设置用户签名
git config --global user.email 邮箱 设置用户签名 - git init 初始化本地库
- git status 查看本地库状态
- git add 文件名 添加到暂存区
git commit -m “日志信息” 文件名 提交到本地库 - git reflog 查看历史记录
git reset --hard 版本号 版本穿梭
设置用户签名
Git 首次安装必须设置一下用户签名,否则无法提交代码。
(这里设置用户签名和将来登录 GitHub(或其他代码托管中心)的账号没有任何关系)
签名的作用是区分不同操作者身份。用户的签名信息在每一个版本的提交信息中能够看到,以此确认本次提交是谁做的。
git config --global user.name 用户名
git config --global user.email 邮箱
初始化本地库
在git bash中进入自己的项目路径,输入如下命令
git init
查看本地库状态
git status
首次查看(工作区没有任何文件),返回:
On branch master
No commits yet
nothing to commit (create/copy files and use “git add” to track)
新增文件(hello.txt) 后,再次查看,返回:
On branch master
No commits yet
Untracked files:
(use “git add …” to include in what will be committed)
hello.txt
nothing added to commit but untracked files present (use “git add” to track)
添加暂存区
git add 文件名
执行git add hello.txt后再次查看git status ,返回:
On branch master
No commits yet
Changes to be committed:
(use “git rm --cached …” to unstage)
new file: hello.txt
提交本地库
记法:-m的m是message
git commit -m "日志信息" 文件名
//案例
git commit -m "my first commit" hello.txt
修改文件
修改文件后,git status查看状态(黑体处为红色):
On branch master
Changes not staged for commit:
(use “git add …” to update what will be committed)
(use “git checkout – …” to discard changes in working directory)
modified: hello.txt
no changes added to commit (use “git add” and/or “git commit -a”)
将修改的文件再次添加暂存区:
git add hello.txt
查看状态(黑体处为绿色)
On branch master
Changes to be committed:
(use “git reset HEAD …” to unstage)
modified: hello.txt
版本穿梭
git reflog #查看历史记录
git reset --hard 版本号 #版本穿梭
Git 分支操作
git branch 分支名 创建分支
git branch -v 查看分支
git checkout 分支名 切换分支
git merge 分支名 把指定的分支合并到当前分支上
合并分支
在 master 分支上合并 hot-fix 分支
xxxx@xxxx MINGW64 /d/Git/branch-merge (master)
$ git merge hot-fix
返回:
Auto-merging hello.txt
CONFLICT (content): Merge conflict in hello.txt
Automatic merge failed; fix conflicts and then commit the result.
产生冲突
冲突产生的表现:后面状态为 MERGING
xxxx@xxxx MINGW64 /d/Git/branch-merge (master|MERGING)
冲突产生的原因:
合并分支时,两个分支在同一个文件的同一个位置有两套完全不同的修改。我们必须自己决定新代码内容。
解决冲突
编辑有冲突的文件,删除特殊符号,决定要使用的内容
特殊符号:
<<<<<<< HEAD 当前分支的代码
====== 合并过来的代码
>>>>>>> hot-fix
添加到暂存区:git add hello.txt
执行提交(注意:此时使用 git commit 命令时不能带文件名)
git commit -m "merge hot-fix"
远程仓库操作
git remote -v #查看当前所有远程地址别名
git remote add 别名 远程地址 #起别名
git push 别名 分支 #推送本地分支上的内容到远程仓库
git clone 远程地址 #将远程仓库的内容克隆到本地
git pull 远程库地址别名 远程分支名 #将远程仓库对于分支最新内容拉下来后与当前本地分支直接合并
SSH 免密登录
按下面的代码一行行执行下去
cd # 删除.ssh 目录
rm -rvf .ssh
ssh-keygen -t rsa -C 邮箱 #填你自己的邮箱
cd .ssh
ll -a
cat id_rsa.pub
复制 id_rsa.pub 文件内容,登录 GitHub
点击用户头像→Settings→SSH and GPG keys→New SSH key
在 Title 中随意取名,在将id_rsa.pub内容复制到Key中
接下来再往远程仓库 push 东西的时候使用 SSH 连接就不需要登录了。