簡介
GIT是一個分布式版本控制軟件,2005年發布。
之前的版本控制工具: CVS、Subversion、SVN。
通過GIT進行版本控制的源代碼托管服務的主流網站有Github、Gitlab、Bitbucket。
國產的托管平臺有:碼云,coding。
git工具:命令行,編輯器集成,github客戶端等方式。
Git很強大,也很簡單。全部命令非常多,但完成日常工作只需要掌握 極其少數的命令即可。其他的可以在工作中遇到調整再去學習。建議初學者使用命令行操作, 使用客戶端僅查看變化以便理解git的作用。
安裝
- GIT客戶端
- Mac用戶安裝XCode之后執行GIT命令會提示安裝
作用
- GIT的作用主要有兩個:文件管理,多人協作。
文件管理:GIT在不斷的備份文件(GIT內部實際上使用的是diff存儲每次的更改而不是真正的備份全部)。
多人協作:GIT通過代碼合并,分支管理等功能讓多名參與者同時開發項目。
核心概念
workspace 工作區
stage 暫存區
repository 本地倉庫
remote 遠程倉庫
總的來說分為遠程倉庫和本地倉庫,遠程倉儲用來儲存項目的最新代碼,本地倉儲用來個人開發,個人可以從遠程pull最新的代碼,也可以將自己修改的代碼push到遠程倉儲。
術語
單詞 | 釋義 | 單詞 | 釋義 |
---|---|---|---|
repository | 版本庫 | branch | 分支 |
checkout | 撤銷 | reset | 重置 |
log | 日志 | merge | 合并 |
stash | 隱藏 | drop | 放棄 |
push | 推送 | pull | 拉 |
GIT常用命令
安裝和配置
-
git help :git子命令和核心概念一覽表
- git help [subcommand]:查看指定git子命令的簡介
-
git config
- git config --list 查看git配置列表
- git config -e [--global] 查看編輯git配置文件
- git config user.name "YOUR_NAME" 查看/設置用戶名(當前項目)
- git config user.email "YOUR_EMAIL" 查看/設置用戶郵箱(當前項目)
- git config --global user.name "YOUR_NAME" 查看/設置用戶名(全局)
- git config --global user.email "YOUR_EMAIL" 查看/設置用戶郵箱(全局)
vim ~/.gitconfig:git配置文件
拉取項目
- git clone [URL]
作為一個初學者可以去github上面新建一個賬號,隨意折騰。
文件操作
git add .
git add [file1] [file2]
git add [dir1] [dir2]
git rm:刪除文件或文件夾
git rm .
git rm [file1] [file2]
git rm --cached [file1] [file2] 從版本控制中移除但保留文件
-
git mv:重命名
- git mv [file1] [file2]
很多人誤認為git add . 中的 . 是所有的意思。其實, . 指的是相對路徑,即當前目錄的意思。
提交代碼
- git commit :提交指定文件或者目錄到本地倉庫
- git commit - m ’注釋‘
- git commit [file] [folder] -m ‘注釋’
- git commit -am ‘注釋’ 提交工作區自上次commit之后的變化,直接到倉庫區
- git commit -amend -m [message] 使用一次新的commit,替代上一次的提交
撤銷
-
git checkout
- git checkout .
- git checkout [file1] [file2]
- git checkout [commit_id] [file]
-
git reset
- git reset [file1] [file2]
- git reset --hard
- git reset [commit_id]
- git reset --hard [commit_id]
隱藏
- git stash
- git stash
- git stash list
- git stash pop
- git stash prod
tip:很容易忘記你隱藏了什么,慎用~
查看信息
git status
-
git diff
- git diff :顯示本地工作區和遠程工作區的差異
- git diff [file] : 本地倉儲指定文件和遠程倉儲的指定文件的差異
-
git log
- git log :顯示commit歷史
- git log --stat :顯示commit歷史應每次commit所變更的文件
- git log -p [files] :顯示指定文件每次commit的diff
- git log -[number] --pretty --oneline:顯示最近number次的log
-
git show
- git show [commit_id] :顯示指定commit_id的diff
- git show [commit_id] [file] :顯示指定commit_id下指定文件的diff
分支
-
git branch
- git branch :顯示本地分支列表
- git branch -r :顯示遠程分支列表
- git branch -a :顯示本地+遠程倉儲的分支列表
- git branch [branch_name]:新建分支,不切換分支
- git branch [branch_name] [commit_id]:新建分支,并指向指定commit_id
- git branch -d [branch_name]:刪除分支
git checkout
git checkout [branch_name] :切換到指定的分支
git checkout -b [branch_name] :新建分支并且切換到該分支
git checkout - :切換到上一次所在的分支
-
git cherry-pick
- git cherry-pick [commit_id] : 將其他分支的commit提交到當前分支
-
git merge
- git merge [branch_name] : 合并指定分支到當前分支
遠程同步
- git pull
- git pull [remote] [branch_name] :拉取遠程庫中的指定分支與本地分支合并
- git push
- git push origin [branch_name] :把當前分支與遠程分支合并
遠程倉庫(即remote)的名字一般都是 origin
參考資料
此文章為作者在學習過程中的總結,用來分享學習。如有錯誤還請指出。謝謝!