Git的使用
workspace:工作区
staging area:暂存区/缓存区
local repository:版本库或本地仓库
remote repository:远程仓库
一、Git创建仓库
1、git init 初始化一个Git 仓库 ,执行完成后会生成一个.git目录
git init - 初始化仓库。
git add . - 添加文件到暂存区。
git commit - 将暂存区内容添加到仓库中。
git status - 查看仓库当前的状态,显示有变更的文件。
git diff - 查看仓库当前的状态,显示有变更的文件。
git reset - 回退版本
git rm - 删除工作区文件
git mv - 移动或重命名工作区文件
git log - 查看历史提交记录
git blame <file> - 以列表形式查看指定文件的历史修改记录
git remote - 远程仓库操作
git fetch - 从远程获取代码库
git pull - 下载远程代码并合并
git push - 上传远程代码并合并
2、git 分支管理
创建分支命令:
git branch (branchname)
切换分支命令:
git checkout (branchname)
合并分支命令:
git merge
列出分支:
git branch
删除分支命令:
git branch -d (branchname)
分支合并
一旦某分支有了独立内容,你终究会希望将它合并回到你的主分支。 你可以使用以下命令将任何分支合并到当前分支中去:
git merge
$ git branch
* master
newtest
$ ls
README test.txt
$ git merge newtest
Updating 3e92c19..c1501a2
Fast-forward
runoob.php | 0
test.txt | 1 -
2 files changed, 1 deletion(-)
create mode 100644 runoob.php
delete mode 100644 test.txt
$ ls
README runoob.php
以上实例中我们将 newtest 分支合并到主分支去,test.txt 文件被删除。
合并完后就可以删除分支:
$ git branch -d newtest
Deleted branch newtest (was c1501a2).
删除后, 就只剩下 master 分支了:
$ git branch
* master
3、Git 查看提交历史
git log - 查看历史提交记录。
git blame <file> - 以列表形式查看指定文件的历史修改记录。
Git标签
git tag -a v1.0
查看所有标签
git tag
4、Git remote命令
git remote 命用于在远程仓库的操作。
显示所有远程仓库:
git remote -v
以下我们先载入远程仓库,然后查看信息:
git clone https://github.com/tianqixin/runoob-git-test
cd runoob-git-test
git remote -v
origin https://github.com/tianqixin/runoob-git-test (fetch)
origin https://github.com/tianqixin/runoob-git-test (push)
origin 为远程地址的别名。
显示某个远程仓库的信息:
git remote show [remote]
例如:
git remote show https://github.com/tianqixin/runoob-git-test
remote https://github.com/tianqixin/runoob-git-test
Fetch URL: https://github.com/tianqixin/runoob-git-test
Push URL: https://github.com/tianqixin/runoob-git-test
HEAD branch: master
Local ref configured for 'git push':
master pushes to master (local out of date)
添加远程版本库:
git remote add [shortname] [url]
shortname 为本地的版本库,例如:
提交到 Github
git remote add origin git@github.com:tianqixin/runoob-git-test.git
git push -u origin master
其他相关命令:
git remote rm name # 删除远程仓库
git remote rename old_name new_name # 修改仓库名
5、git push 命令
git push 命用于从将本地的分支版本上传到远程并合并。
命令格式如下:
git push <远程主机名> <本地分支名>:<远程分支名>如果本地分支名与远程分支名相同,则可以省略冒号:
git push <远程主机名> <本地分支名>
实例
以下命令将本地的 master 分支推送到 origin 主机的 master 分支。
$ git push origin master
相等于:
$ git push origin master:master
如果本地版本与远程版本有差异,但又要强制推送可以使用 --force 参数:
git push --force origin master
删除主机但分支可以使用 --delete 参数,以下命令表示删除 origin 主机的 master 分支:
git push origin --delete master
以我的 https://github.com/tianqixin/runoob-git-test 为例,本地添加文件:
$ touch runoob-test.txt # 添加文件
$ git add runoob-test.txt
$ git commit -m "添加到远程"
master 69e702d] 添加到远程
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 runoob-test.txt
$ git push origin master # 推送到 Github
将本地的 master 分支推送到 origin 主机的 master 分支。
重新回到我们的 Github 仓库,可以看到文件已经提交上来了