PoChunChen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Linux 核心設計 / Git基本功能教學 description: tags: Linux Kernal --- # Git基本功能教學 主要內容節錄至 YouTube頻道-李祐棠: [Git中文教學](https://www.youtube.com/watch?v=LZ4oOzZwgrk&list=PLlyOkSAh6TwcvJQ1UtvkSwhZWCaM_S07d&index=1) ## 1. 安裝與設定 ### Git useful tool 圖形介面程式 1. Linux : gitk(built-in) 2. MacOS : gitx ### Start a Project * Simple * `git init` * `git add <file>` * `git commit` * Setup user name and email * `git config user.name` * `git config user.email` --- * Setup editer * `git config core.editor vim` * Setup merge tool * `git config merge.tool vimdiff` * Setup alias (快捷名稱設定) * `git config alias.xxx yyy` * Setup color * `git config color.ui true` 補充:`git config --global` 可以一次性更改所有 git 設定。 --- ## 2. Add and Commit ![](https://i.imgur.com/wZ866ti.png) ![](https://i.imgur.com/v9nyJqV.png) 而 `git commit` 是把 staged 的東西移到 commit 資料庫內。 * **`git commit -a`** 將 `git commit` + `git add` 兩個動作一次完成。 * See your repository status by `git status` * git add * `git add -p` 分別檢視與是否加入**每一個改變**,這就是 patch add 。 * git commit * 50/72 rule * As detailed as possible ### 常用指令: * 查看狀態 ``` $ git status ``` ![](https://i.imgur.com/Bdz7N0G.png) * Changed to be committed: >已經透過 `git add` 把需要加入的修改項目,添加到下一次的 Commit (等待發送的)當中。 * Changes not staged for commit: >代表 GitHub 上面有這個檔案,但是還在 Commit 中(還沒更新到 Git 上面的意思)。 * Untracked files: >代表 GitHub 上面還沒有這個檔案。 * 加入想要 Commit 的修改項目 * 全部修改皆加入 ``` $ git add ``` * 逐一審查要加入的修改 ``` $ git add -p ``` * log 查看版本紀錄 ``` $ git log ``` * ignore (不要出現在 status 的方法) 1. 產生一個 `gitignore` ,裡面 ``` $ vim .gitignore ``` >在欲加入 `gitignore` 的檔案,加上 `/` 後為現在這個資料夾下的那個檔案 >``` >/檔名 >``` 2. 將新建的 `gitignore` 檔案加入 Commit 中 ``` $ git add .gitignore ``` 如果要取消加入 ``` $ git reset HEAD .gitignore ``` [該 ignore 什麼的參考資料](https://github.com/github/gitignore) [Git:--local-branching-on-the-cheap](https://git-scm.com/book/en/v2) ### 重要守則 1. 不要留下個人機密資料(因為幾乎刪不掉) 2. 不要放上非必要的大檔案 3. Generated files(產生的檔案,例如執行檔) ### 50/72法則 在 Commit 中,遵從標題,內文72字的規則,標題清楚標,細節在內文。會有字數限制是因為,在終端機用 `$ git log` 閱讀 Commit 時,這樣可以一行看完,而不會有些 Commit 標題一行,有些兩行。 >標題在超過字數(50字)後,文字會變成白色提醒使用者。 撰寫 Commit 建議須包含以下: 1. 議題編號: `Relate Issue: Issue #159` 2. 問題敘述: `The Problem:` 3. 原因解釋: `The Cause:` 4. 解決方式: `The fix:` :::spoiler 建議範本 ```commit Relate Issue: Issue #159 The Problem: The following source code will create wrong branch arrow. var graph1 = new GitGraph({ elementId: 'badGraph', mode: 'compact', template: 'blackarrow' }); var m1 = graph1.branch("master"); m1.commit(); var r1 = m1.branch('1.0.x'); m1.commit(); r1.commit(); The arrow pointed to r1 commit will pointed from second commit of m1 not follow the line from first commit of m1. The Cause: When create a commit, if user does not specify parent commit in options gitgraph.js will execute following code: options.parentCommit = options.parentCommit || _getParentCommitFromBranch(this); to determine the parent commit of the created commit. In the function _getParentCommitFromBranch, it will try to get the last commit from current branch, then from parent branch. Since r1.commit() is the first commit in its branch 1.0.x, it will set its parent commit to last commit of its parent branch, that is master. And since master already add some new commit, the arrow will point from wrong commit, the last commit of master branch. There is code that deal with branch case: if (options.parentCommit instanceof Commit === false && this.parentBranch instanceof Branch) { options.parentCommit = this.parentCommit; } It set parentCommit to the correct commit. However, since options.parentCommit already been set by previous code, this code will never execute since options.parentCommit is always a Commit. The fix: The fix is combining two scenario. If current branch already has commits, the parentCommit will be set to last commit in this branch. Otherwise, it will set to parent commit of this branch, which will be the correct commit instead of last commit of parent branch. ``` [參考資料:fix wrong arrow angle on branching #171](https://github.com/nicoespeon/gitgraph.js/pull/171) ::: ### 偉大 Git commit message 的七條規則 1. 用一行空白行分隔標題與內容 2. 限制標題最多只有 50 字元 3. 標題開頭要大寫 4. 標題不以句點結尾 5. 以祈使句撰寫標題 6. 內文每行最多 72 字 7. 用內文解釋 what 以及 why vs. how ## 3. Indicate a Commit Hash Value: 指定是哪個Commit。 * `-(n)` :只顯示最後 n 筆提交。 ``` $ git log -n1 ``` * `HEAD` 、`master` 目前的commit。 ``` $ git log -n1 HEAD ``` ``` $ git log master ``` * `^` 看目前 Commit 的舊一個。 * `--oneline` 只顯示一行。 * `$ git log --oneline load.cpp` : 只顯示與 `load.cpp` 有關的 Commit。 * `Git log <path>|<commit>` * -n : limit number * __oneline : view hash and commit summary * --stat : view files change * --patch : view lines change * -S or --grep : find modification --- * `diff` :顯示改了什麼( Commit 與未加入 Commit 的不同)。 > ``` $ git diff ``` ##### 參考資料: [Git 基礎 - 檢視提交的歷史記錄](https://git-scm.com/book/zh-tw/v2/Git-基礎-檢視提交的歷史記錄) ## 4. Patch Add and Amend * Git add -p * My experience: always use this * this hunk from worktree [y,n,q,a,d,/,j,J,g,s,e,?]? * s: seperate all change parts * e: edit Modify Commit 1. Use git commit -- amend a. Check before doing this 2. Use reset HEAD^ then re-commit ![](https://i.imgur.com/A7Z3aMx.png) ## 5. Branch and Merge ### Move and Create Branch * Checkout: move HEAD * `git checkout <commit>` Move to HEAD * `git checkout <path>` WARNING: discard change * Branch: * `git branch` List branch * `git branch <name>` Create branch * Or just: `git checkout -b` * 綜合開新的Branch和移動HEAD到新增的Branch * `git checkout -b <name>` ### View Branch * `git branch` * `git log ru8 加下面` * --decorate (看 reference 用的,若無效輸入下面那行) * config log.decorate auto * --graph ### Delete Branch * `git branch -d <name>` * `git branch -D <name>` for no-merge commit * WARNING: Discard Commit ### Merge * `git merge <branch>` * Usually mainline merge other * `git checkout master` * `git merge <branch>` ### Resolve Conflict * Manually resole * Check evert codes between `<<<<<<`, `>>>>>>` * Edit code to what it should be * Use `git mergetool` (圖形化介面,展示哪裡不同) like vimdiff * It shows: local, base, remote, file to be edited * Edit "file to be edited" to what is should be * Add and commit ![](https://i.imgur.com/Cc2609Y.jpg) 上圖的意思: `<<<<<<` 未修改的版本 `======` 新改的地方 `>>>>>>` 去對照後,手動改成最新版的,再 commit 。 ### Reference * https://git-scm.com/book/en/v2 * 3.1 Branches in a Nutshell * 3.2 Basic Branching and Merging * https://yodalee.blogspot.com/2013/03/vimdiffgit-merge-conflict_28.html ## 6. Rebase ### Rebase: Why and What * Move your branch to another place * Clean up your DAG (Directed Acyclic Graph) / Edit commits * Main branch has updated, rebase feature branch to new master ![](https://i.imgur.com/T51OeQM.png) ### What Rebase Do 1. Checkout the new-base 2. Re-apply commits ![](https://i.imgur.com/49xRSlI.png) ### Rebase: How * Rebase <new_base> * Rebase current branch to <new_base> * Start from `git merge-base HEAD <new-base>` * `rebase --onto <new base><ref_commit><branch>` * Rebase from common ancestor of `<ref_commit>` and `<branch>` Example: * `git rebase --onto master A dev` * Notice the Hash Value ![](https://i.imgur.com/ATsqdAd.png) ### Rebase: Conflict * Rebase stop if conflict * A little different to merge case: just add the final result * `git rebase --continue` until end * `git rebase --abort` if out of control ### Rebase -i * Change content (edit) * Change message (reword): 修改 Commit message * Change order: 直接在介面裡面換順序就好 * Remove commit (drop) * Combine commit (squash, fixup) * Split (edit->reset) * Run command (exec) ### Some Tips * Rebase can do fast-forward if new base is child of current branch * Just forward reference ### Thing to Notice * Rebase is re-commit, it changes histoy * ==Do not rebase on published commits== * Prevent rebase across branch base * Suggest making a ==backup before rebase== ### Reference * https://git-scm.com/book/en/v2 * 3.6 Rebasing * https://blog.yorkxin.org/posts/git-rebase/ ## 7. Remote and Github ### Clone and Remote * `git clone` * Default remote name is origin * Remote: * `git remote show <origin>`: list detail * `git remote add <name>`URL: add remote * `git remote rename <a><b>`: rename ### Remote is Reference * Remote branch is named by: `<remote>/<branch>` * Show hidden branch by `branch -a` ### Update Status * fetch remote * `git fetch <name>` * Rebase local branch to remote state Or * Just `pull`(=fetch + rebase) ### Push * `git push <remote><branch>`: `<branch>` * `--set-upstream` * `git push <remote>`: `<branch>` delete remote branch ### basic Workflow * Fork on Github, clone your repository as `<origin>` * Add `<upstream>` * Develop on mew branch * Push branch to `<origin>`, open Pull Request * After merge, fetch `<upstream>` and rebase master ### Reference * https://git-scm.com/book/en/v2 * 2.1 Getting a Git Repository * 5.2 Contributing to a Project * http://yodalee.blogspot.tw/2014/05/pull-requestgithub.html ## 8. Stash ### Why Stash * Temporarily store your work not enough for commit ### Usage * `git stash`: store stash content * `git stash list`: show stored content * Use `stash@{n}` to indicate stash * `git stash pop`: pop top * `git stash drop`: drop stash WARNING ### Reference * https://git-scm.com/book/en/v2 * 7.3 Stashing and Cleaning * http://yodalee.blogspot.tw/2013/12/git-stash.html ## 9. Patch and Cherry-Pick ### Generate Patch * `git format-patch <base_commit>` * `git format-patch -n3 <top_commit>` Or * `git diff > name.patch` ### Apply Patch (貼上去) * `git apply <patch>`: apply patch * `git apply --check`: check no conflict * Commit after apply * `git am`: apply and commit * `git am *.patch` is very useful ### Patch Conflict * `git apply --reject <patch>` * Patched failed stored in file.rej * Manual resolve the conflict, then `git am --continue` ### cherry-pick * `git cherry-pick <commit>` * Resolve conflict like rebase, just ass then `git cherry-pick -- continue` ### Reference * https://git-scm.com/book/en/v2 * 5.3 Maintaining a Project * http://yodalee.blogspot.tw/2017/03/git-patch.html ## 10. Bisect and Blame ### Serch for Modification * `git blame -L <start>,<end> <file>` * `git blame -L`: `<function> <file>` ### Bisect Find where program failed 1. `git bisect start` 2. `git bisect good <commit>` 3. `git bisect bad <commit>` ... Do binary search, mark good, bad... Or * Just `git bisect run <shell>` ### Refernece * https://git-scm.com/book/en/v2 * 7.10 Debugging with Git * http://yodalee.blogspot.tw/2014/08/git-bisect.html ## 11. Ending ### Not Mention * Open your own derver * Manage branch on local or server * Use git with SVN server * Submodule * Tag * Save deleted data * Modify history

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully