Skip to content

git常用指令

以下是整理好的 Git 指令表,已經依照 workspacestaginglocalremote 四個部分分類,並且說明每個指令如何改變這些區域的資料。另外也補充了 stash,因為它在特定場合非常實用。

Git 指令表

Git 指令 區域影響 說明
git init local 初始化一個新的 Git 儲存庫,建立 .git 目錄,並在本地創建一個新的儲存空間 (local)。
git clone <url> workspace, local, remote 從遠端儲存庫複製整個專案到本地 (local),並在 workspace 中建立副本。
git add <file> staging 將指定檔案從 workspace 加入到 staging (暫存區),準備提交 (commit)。
git add . staging 將 workspace 中所有變更的檔案加入到 staging。
git status workspace, staging 顯示 workspace 和 staging 的狀態,告訴你哪些檔案被修改、哪些已被加入 staging。
git commit -m "訊息" local 將 staging 區域的內容提交到 local 儲存庫,生成一個新的 commit。
git commit --amend local 修改上一次的 commit 訊息或加入新變更,不影響 staging 和 workspace。
git diff workspace 比較 workspace 和 staging 之間的差異。
git diff --staged staging 比較 staging 和 local 之間的差異。
git log local 查看 local 的 commit 歷史。
git push origin <分支> remote 將 local 儲存庫的指定分支推送到 remote (遠端儲存庫)。
git pull origin <分支> workspace, local, remote 從 remote 拉取最新的版本並合併到 local 和 workspace。
git fetch remote 從 remote 下載最新的版本到 local (但不會更新 workspace)。
git merge <分支> local 將指定分支的變更合併到目前所在的分支 (local)。
git checkout <分支> workspace 切換到指定的分支,並更新 workspace 中的檔案。
git branch local 列出 local 中所有的分支。
git branch <分支名> local 在 local 中建立一個新的分支。
git reset HEAD <file> staging 將檔案從 staging 移除,但不會影響 workspace。
git reset --soft <commit> local 將 local 的 HEAD 移動到指定的 commit,但保留 staging 和 workspace 的變更。
git reset --mixed <commit> local, staging 將 HEAD 移動到指定的 commit,並將變更移除 staging,但保留 workspace。
git reset --hard <commit> local, staging, workspace 將 HEAD、staging 和 workspace 全部重置為指定的 commit (謹慎使用)。
git stash stash 將目前 workspace 和 staging 的變更暫存起來,保持乾淨的工作區。
git stash apply workspace, staging 將 stash 中的暫存變更取回到 workspace 和 staging,但不刪除 stash。
git stash pop workspace, staging 將 stash 中的暫存變更取回到 workspace 和 staging,並刪除該暫存。
git stash list stash 列出所有 stash 暫存的變更清單。
git stash drop stash 刪除指定的 stash。

區域解釋

  • Workspace:目前你正在編輯的檔案所在的工作目錄。
  • Staging (Index):已經準備好提交的變更區域。
  • Local (Repository):本地儲存庫中保存的完整版本歷史。
  • Remote (Repository):遠端儲存庫,例如 GitHub、GitLab 等平台上的專案。
  • Stash:暫存區域,用於臨時存放未完成的變更。