ก่อนสร้าง commit ต้อง add ไฟล์ที่แก้ไขเข้า commit ก่อน รันคำสั่ง git status ก่อน add ไฟล์ จะเห็นข้อความ changes not staged for commit ใน output
คู่มือนี้อธิบายความหมายและความสำคัญของข้อความนี้ พร้อมตัวอย่างการ stage ไฟล์เพื่อ commit
changes not staged for commit
ไฟล์ใน Git repository สามารถอยู่ใน 3 สถานะ: ignored, ใน staging area, หรือเป็นส่วนของ commit
- Ignored files: ไม่รวมใน record ของ Git repository
- Staging area: ไฟล์ที่จะถูกเพิ่มเข้า commit ถัดไป
Staging area สำคัญเพราะให้เลือกว่าไฟล์ไหนควร/ไม่ควรเข้า commit สามารถ add/remove ไฟล์จาก staging area ได้ตลอดก่อนสร้าง commit
Staging area เหมือนพื้นที่ triage หากพบไฟล์เพิ่มเติมที่ควรเข้า commit ให้ add เข้า staging แล้วค่อยสร้าง commit เมื่อมั่นใจครบ
ตัวอย่างสถานการณ์ (An Example Scenario)
ต้องแก้ไขไฟล์ใน Git repository ก่อน จะได้ข้อความนี้ สมมติมี repo พร้อมไฟล์ README.md ว่าง เปลี่ยนเนื้อหาเป็น:
# Example Repo
รัน git status ดูสรุปไฟล์ที่เปลี่ยน:
git status
ผลลัพธ์:
On branch master Your branch is up to date with 'origin/master'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: README.md
Git บอกว่าอยู่ branch master, branch ปัจจุบัน up-to-date กับ remote มีไฟล์เปลี่ยน 1 ไฟล์: README.md ยังไม่ add เข้า staging area หรือ commit working directory modified
เพื่อทำให้ข้อความหาย ให้ add README.md เข้า staging area:
git add README.md
คำสั่งเลือกไฟล์เข้า commit ได้ แล้วสร้าง commit:
git commit -m "docs: Update README.md"
สร้าง record สถานะ repository พร้อมการเปลี่ยนแปลงใน staging area หากมี remote repo ให้ push:
git push
การเปลี่ยนแปลงอยู่ local และ remote แล้ว
ตรวจสอบ git status อีกครั้ง:
On branch master Your branch is up to date with 'origin/master'. nothing to commit, working tree clean
บอกว่าไม่มีการเปลี่ยนแปลงที่ยังไม่ add เข้า commit หรือ staging area หมายถึงแก้ไขสำเร็จ มี commit ใหม่เพิ่มขึ้น 1 commit ที่มีการเปลี่ยนแปลง README.md
สรุป
ข้อความ changes not staged for commit แสดงเมื่อรัน git status และมีไฟล์ที่เปลี่ยนแปลงแต่ยังไม่ add เข้า staging area
นี่ไม่ใช่ error message แค่แจ้งเตือนว่ามีไฟล์เปลี่ยนแปลงไม่อยู่ใน staging area หรือ commit ทำให้หายไปได้โดย add ไฟล์เข้า commit และ commit ไป repository ตอนนี้คุณรู้จักจัดการข้อความ Git นี้อย่างมืออาชีพแล้ว!