Git and GitHub Basics
Commits and History
In this lesson you will
- Save a snapshot with git add and git commit
- Explain the staging area
- Read history with git log and git diff
Introduction
A commit is a saved snapshot of your project. Making good commits is the heart of using Git. The cycle is small and repeatable: change files, choose what to save, then save with a message.
The simple explanation
You add the changes you want to a waiting area, then commit them with a message.
The waiting area is called the staging area. It lets you decide exactly what goes into the next snapshot, like packing a box before you seal it.
The commit cycle
Create a file, then save it as a commit:
Terminal
# make a file
echo "Hello Git" > hello.txt
# see that Git notices a new file
git status
# put the file in the staging area
git add hello.txt
# seal the snapshot with a message
git commit -m "Add hello file"Write commit messages that say what changed and why, in the present tense, such as "Add login form" or "Fix typo in heading". Future you will thank you.
Quick quiz
What does git add do?
Look at your history
Terminal
# list past commits in a short form
git log --oneline
# see exactly what you changed but have not staged yet
git diff
# see what is staged for the next commit
git diff --stagedEach commit has a short code called a hash, such as a1b2c3d, that identifies it. The output looks like a list of those codes followed by the messages.
Fixing mistakes safely
- Changed a file and want to throw the change away?
git restore hello.txtreturns it to the last commit. This discards your edits, so use it with care. - Staged a file by mistake?
git restore --staged hello.txttakes it out of the staging area but keeps your edits.
Ignore files you do not want tracked
Create a file named .gitignore and list things Git should skip, such as passwords files, build folders or node_modules/. Never commit secrets like passwords or API keys. Once pushed to a public site, a secret should be treated as exposed.
Try it yourself
Make a new file, add two lines of text, commit it, then change one line and view git diff. Commit again and look at git log --oneline. You should see two commits.
Summary
- Work in a cycle: change,
git add,git commit -m "message". - The staging area lets you choose what goes into each snapshot.
- Use
git log --onelineandgit diffto see history, and never commit secrets.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading