iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0
自我挑戰組

30天 Git 版本控制實戰筆記系列 第 9

Day 9:Git Stash 暫存技巧 - 工作切換神器

  • 分享至 

  • xImage
  •  

今日目標
• 掌握 Git Stash 處理工作中斷情況
• 學習職場中的緊急任務切換技巧
• 建立多功能並行開發的管理能力
• 體驗真實企業開發的工作節奏
為什麼需要 Git Stash?
職場真實情況:
你正在寫程式碼...

突然!主管:「緊急!網站登入壞了,立刻修復!」

但你的程式碼寫到一半,還不能 commit

需要立即切換去處理緊急問題

Git Stash 拯救了你!
常見的工作中斷場景:
• 🚨 緊急 Bug 修復:線上系統出問題,需要立即處理
• 👥 同事求助:需要幫忙檢查另一個分支的程式碼
• 📞 客戶緊急需求:臨時要展示某個功能給客戶看
• 🔄 程式碼衝突:要 pull 最新版本但本地有修改
操作步驟
步驟1:建立開發環境

確保在專案資料夾

cd company-website
git checkout main
git pull origin main

建立新功能分支(模擬開發新功能)

git checkout -b feature/user-profile

查看分支狀態

git branch
步驟2:開始開發個人資料頁面功能
建立 profile.html:

<h1>個人資料設定</h1>

<form class="profile-form">
    <div class="form-group">
        <label>姓名:</label>
        <input type="text" id="username" value="">
    </div>
    
    <div class="form-group">
        <label>電子郵件:</label>
        <input type="email" id="email" value="">
    </div>
    
    <div class="form-group">
        <label>電話:</label>
        <input type="tel" id="phone" value="">
    </div>
    
    <!-- TODO: 還要加入更多欄位 -->
    <!-- TODO: 加入頭像上傳功能 -->
    
    <button type="submit">儲存設定</button>
</form>

.form-group {
margin-bottom: 15px;
}

.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}

.form-group input {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}

/* TODO: 還要加入更多樣式 /
/
TODO: 響應式設計 */
步驟3:檢查開發進度(程式碼寫到一半)

查看目前修改狀態

git status

查看具體修改內容

git diff

你會看到新增了 profile.html,css 也有修改

但功能都還沒完成,到處都是 TODO

Git Stash 實戰操作
步驟4:模擬緊急工作中斷
💥 突發狀況:
主管急忙跑來:「緊急!客戶反映首頁的聯絡按鈕連結錯誤!
客戶點了沒反應!需要立刻修復!」

你看看螢幕:個人資料頁面才寫一半...

  • HTML 結構不完整
  • CSS 樣式還在調整
  • 到處都是 TODO 註解
  • 表單功能還沒寫

現在不適合 commit,但又必須立即處理緊急問題!
步驟5:使用 Git Stash 暫存工作

暫存所有工作(包含新建立的檔案)

git stash push -u -m "開發中:個人資料頁面 - 基本結構完成,表單功能待開發"

確認工作目錄變乾淨

git status

查看暫存清單

git stash list
步驟6:處理緊急修復

切換回 main 分支

git checkout main

建立緊急修復分支

git checkout -b hotfix/contact-button-link
修復 index.html 的聯絡按鈕:

.btn {
background-color: #007bff;
color: white;
padding: 12px 24px;
text-decoration: none;
border-radius: 5px;
display: inline-block;
}

.btn:hover {
background-color: #0056b3;
}
步驟7:提交緊急修復

檢查修復內容

git status
git diff

加入修復

git add .

提交緊急修復

git commit -m "hotfix: 修復首頁聯絡按鈕連結錯誤

  • 修正聯絡按鈕的 href 連結
  • 加入聯絡按鈕樣式
  • 改善使用者體驗

緊急修復客戶回報的按鈕問題"

推送緊急修復

git push origin hotfix/contact-button-link
步驟8:回到原本工作

模擬 PR 被快速核准並合併後

切換回開發分支

git checkout feature/user-profile

查看 stash 清單

git stash list

恢復之前的開發工作

git stash pop

檢查工作恢復狀況

git status

你會發現之前開發到一半的個人資料頁面完整恢復了!

今日重點回顧
• ✅ 學會用 Git Stash 處理工作中斷
• ✅ 掌握緊急任務的切換流程
• ✅ 理解基本的暫存管理技巧
• ✅ 建立職場實戰的操作習慣
核心指令總結
git stash push -u -m "描述" # 暫存工作(包含新檔案)
git stash list # 查看暫存清單
git stash pop # 恢復最新暫存(並刪除)
git stash drop stash@{0} # 刪除特定暫存


上一篇
Day 8:Pull Request 工作流程與 Code Review
系列文
30天 Git 版本控制實戰筆記9
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言