tech katta

Everyday Git: init, clone, status, add, commit, log, diff and .gitignore

Lesson 14 of 23 · 5 min readFree

In this lesson

The handful of Git commands you will use dozens of times a day, how to read their output, and how to keep secrets and build files out of your repository.

On this page
  1. Why this matters
  2. Starting: init and clone
  3. The daily loop
  4. .gitignore: files Git should leave alone
  5. Staging and committing
  6. Reading history
  7. When you commit something you should not have
  8. Fixing the last commit
  9. Other small things you will need
  10. Try it

You now know where changes live. This lesson turns that into a daily routine: start or clone a project, see what changed, commit it in sensible pieces, read the history and keep junk and secrets out. These commands cover most of what a developer does in Git.

Why this matters#

Good everyday habits matter more than rare tricks. A repository with small, clear commits is easy to review and easy to roll back. A repository with one giant "update" commit, or one that has a password buried in its history, is a problem for every teammate and for the server you deploy to. We will also look at what to do when you commit a file you should not have.

All output below comes from a real repository, using Git 2.43. A bare repository on the same machine played the part of the remote server, so we had something to clone.

Starting: init and clone#

You get a repository in one of two ways. git init turns the current folder into a repository. git clone copies an existing repository, with its whole history, from another place.

Shell
git clone origin.git api
cd api
git status
Text
Cloning into 'api'...
warning: You appear to have cloned an empty repository.
done.
On branch main
No commits yet

The remote in this example was empty on purpose, hence the warning. With a real URL, such as git clone https://example.com/team/api.git, you get all the files. A clone remembers where it came from under the name origin, which lesson 17 covers.

The daily loop#

Most of the time you repeat four steps: change files, check, stage, commit. git status is the one you will type most. Start with a few new files in the working tree:

Shell
git status -s
Text
?? .env
?? debug.log
?? node_modules/
?? package.json
?? src/

.env holds a secret, debug.log is a log file and node_modules/ holds downloaded dependencies. None of those belong in the repository. That is what .gitignore is for.

.gitignore: files Git should leave alone#

.gitignore is a text file in your project that lists patterns for files Git should ignore. Commit it, so everyone shares the rules.

Text
node_modules/
.env
*.log
  • A name such as .env matches that file anywhere in the project.
  • A trailing slash, as in node_modules/, matches a folder.
  • * is a wildcard, so *.log matches every log file.
  • A leading ! re-includes something. A # starts a comment.

After creating the file, status no longer lists the ignored files:

Shell
git status -s
git check-ignore -v .env debug.log node_modules/dep/index.js
Text
?? .gitignore
?? package.json
?? src/
.gitignore:2:.env	.env
.gitignore:3:*.log	debug.log
.gitignore:1:node_modules/	node_modules/dep/index.js

git check-ignore -v is useful when a file is being ignored and you do not know why: it names the rule and the line. Commit a file such as .env.example with fake values so a new teammate knows which variables to set.

Ignoring only affects files that are not tracked yet. A file already in the history stays tracked even if you add it to .gitignore later.

Staging and committing#

Stage what you want in the next commit, check, and commit with a message.

Shell
git add .
git status -s
git commit -m "Add API skeleton"
git log --oneline
Text
A  .gitignore
A  package.json
A  src/server.js
f1144da Add API skeleton

git add . stages everything in the current folder, so read git status first to be sure you are not staging something unintended. You can stage a single file with git add src/server.js, or go piece by piece with git add -p, which asks you about each changed chunk.

For files Git already tracks, git commit -am "message" stages all modified tracked files and commits in one step. It does not add new files.

Shell
echo 'app.listen(port);' >> src/server.js
git diff --stat
git commit -am "Start listening on the port"
Text
 src/server.js | 1 +
 1 file changed, 1 insertion(+)
[main 9fc5d7b] Start listening on the port
 1 file changed, 1 insertion(+)

If you run git commit with no staged changes, Git says "nothing to commit, working tree clean" and does nothing. If you run it without -m, Git opens your editor for the message. Lesson 21 covers how to write good messages.

Commit one logical change at a time: a bug fix, a feature step, a rename. If you cannot describe a commit in one short sentence, it is probably two commits.

Reading history#

git log shows commits, newest first. The plain form is long, so these shorter forms are the ones people use:

Shell
git log --oneline
git log -2 --format='%h %s'
git log --oneline -- src/server.js
Text
9fc5d7b Start listening on the port
f1144da Add API skeleton
9fc5d7b Start listening on the port
f1144da Add API skeleton
9fc5d7b Start listening on the port
f1144da Add API skeleton

The third form lists only the commits that touched a file. Other useful options are --stat (files changed per commit), -p (the full patch), --author=name and --since='2 weeks ago'.

git show displays one commit with its changes, and git show HEAD:package.json prints a file as it was in a given commit. HEAD means "the commit you are on now", and HEAD~1 means its parent.

Shell
git show --stat --format='%h %s' HEAD
git diff HEAD~1 --stat
Text
9fc5d7b Start listening on the port

 src/server.js | 1 +
 1 file changed, 1 insertion(+)
 src/server.js | 1 +
 1 file changed, 1 insertion(+)

Use git diff in these forms:

  • git diff compares the working tree with the staging area (changes not yet staged).
  • git diff --staged compares staging with the last commit (what you are about to commit).
  • git diff HEAD compares the working tree with the last commit (everything uncommitted).
  • git diff A B compares two commits.

When you commit something you should not have#

It happens to everyone. We accidentally added .env to a commit. The first step is to stop tracking it and ignore it from now on:

Shell
git rm --cached .env
echo '.env' >> .gitignore
git add .gitignore
git commit -m "Stop tracking .env"
git ls-files
Text
.gitignore
package.json
src/server.js

git rm --cached removes the file from Git's tracking but leaves it on your disk. The file is gone from the latest snapshot. It is not gone from history. The earlier commit still contains it, and anyone who clones can read it with git show. If the commit was pushed, treat the secret as exposed: rotate it (create a new password or key and revoke the old one). Rewriting history to hide it is a bigger operation, and still does not help if someone has already cloned. The safe habit is to set up .gitignore before the first commit and always read git status before committing.

Fixing the last commit#

If you made a typo in the message or forgot to stage a file, you can replace the last commit before you share it:

Shell
git commit --amend -m "Add hello file"

This creates a new commit with a new hash in place of the old one. Only amend commits that you have not pushed. Once other people have the commit, replacing it causes trouble, a problem lesson 18 explains.

Other small things you will need#

  • git mv old new renames a tracked file, and git rm file deletes one. Doing it by hand and then running git add -A records the same thing.
  • git clean -n previews which untracked files git clean -f would delete. Always run the preview first.
  • git blame file shows who last changed each line and in which commit, which helps you find the reason behind a line of code.

Try it#

  1. Create a new folder with package.json, a src/ folder, a .env and a debug.log. Run git init and git status -s. Create a .gitignore for the last two, then check git status -s again.
  2. Commit the files with a clear message. Then change one file and compare git diff and git diff --staged before and after staging it.
  3. Run git log --oneline and git show --stat HEAD. Then view an old version of a file with git show HEAD~1:path.
  4. Commit a file called secret.txt, then stop tracking it with git rm --cached and ignore it. Use git log --stat to confirm it is still in the older commit.
  5. Make a commit with a typo in its message and fix it with git commit --amend. Check that the hash changed.