git學習總結
從svn到git
兩者都是優秀的版本管理工具(giter請不要鄙視svner)
- svn上手非常容易,操作簡單
- git功能強大,但是要熟練使用分支不算容易
git因為是分布式的,所以其核心就是分支(只有master分支情況下和svn差不多?),分支的意義在于,可以將項目代碼按照功能、模塊拆分成不同的分支。比如這個產品要加一個支付功能和一個登陸功能,可以創建兩個分支,交給不同的開發人員并行開發。登陸功能先開發完,測試無誤后合并改分支到 master分支,master分支部署上線。支付功能雖然沒有開發完成,但是在另一條分支上,所以產品上線和功能開發完全不受影響。這才是分布式開發的高效模式。
被git坑了一個星期之后決心把官方文檔看一下,結合實踐經驗進行了整理。
新手常見問題
-
如何查看有哪些分支?
git branch -a -
如何強制檢出/切換分支或分支指定文件
git checkout <branch> [file] [-f]
強制更新,以branch版本的代碼為主 -
提交代碼出現沖突沖突怎么辦?
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
先切換分支,然后拉取分支上最新的代碼覆蓋到本地
git pull
添加或者提交代碼,解決沖突之后
git push -
如何新建分支
git checkout -b <branch_name>
本地建立 branch 並立即切換到新分支
git branch -m <new_name>
修改分支名稱
- 從遠程倉庫拉取代碼到本地倉庫,并建立跟蹤關系
git clone http://xxx.git
或者
get clone git@xxx.git
然后
git checkout -b <本地新分支名> <對應的遠程分支名>
實用指令
reset
git reset [file]
取消暫存
remote
查看遠程倉庫名
git remote -v
查看遠程倉庫url
git remote add <basename> <url>
新增遠程倉庫
git remote show <basename>
查看遠程倉庫詳細信息
git remote rename <old basename> <new basename>
重命名遠程倉庫
pull
相當于fetch和merge
push
git push [remote_branch] [local_branch]
推送本地倉庫代碼到遠程倉庫,相當于svn的commit
git push <remote base> [tag name]
推送本地標簽到遠程倉庫
git push <remote base> <remote branch>:<local branch>
將本地分支推送到指定的遠程分支
git push <remote base> --delete <remote branch>
刪除遠程分支
tag
查看標簽(用來標記標志性的穩定版本信息)
git tag -l '[expression]'
查看那符合正則表達式的
git tag -a <tag name> -m <comment>
添加帶注釋的標簽
git tag -a <tag name> <md5>
對某個版本打標簽
git tag [tag name]
如果沒有標簽名,則為查看所有標簽。帶標簽名則為新建標簽
merge
git merge <branch name>
將其他分支合并到本分支
commit
git commit -a -m 'xx'
暫存并提交
branch
git branch
查看本地倉庫分支
git branch -v
查看本地倉庫分支最后一次提交情況
git branch -vv
查看分支跟蹤情況
git branch <branch name>
新建分支
git branch -d <branch name>
刪除分支
git branch [--merged | --no-merged]
查看已合并|未合并的本地倉庫分支
git branch -u <remote base>/<remote branch>
修改當前跟蹤分支
commit
git commit -a -m 'xx'
提交并且暫存暫存的方法
checkout
git checkout -- [file]
恢復文件
git checkout -b [branchname] [tagname]
在特定的版本上創建一個新的分支并切換到此分支
git checkout -b [local branch] [remote base]/[remote branch]
將遠程分支檢出到本地分支
git checkout --track <remote base>/<remote branch>
讓當前分支跟蹤遠程分支
git checkout --track <remote base>/<remote branch>
git checkout -b <local branch> <remote base>/<remote branch>
讓當前分支跟蹤到遠程分支。兩條命令作用基本一致,不同的是第二條命令可以重命名檢出的分支。
rebase
git rebase [basebranch]
變基是將一系列提交按照原有次序依次應用到另一分支上,而合并是把最終結果合在一起。
小技巧
查看配置
git config -1
設置別名
git config --global alias.<name> <commend>
保存用戶名和密碼
對于http(s)協議,可以用下面命令臨時緩存
git config --global credential.helper cache
開啟linux緩存
git config --global credential.helper wincred
開啟windows緩存