Git guide: everyday commands and practical shortcuts
Git keeps two things in sync that are easy to confuse: the files on your disk and the snapshots inside the repository. Most everyday frustrations, such as "I pushed but GitHub still shows the old code", "I committed the wrong file" or "I want to stop tracking this file", come from mixing those two up. This guide walks through the full daily cycle with copy-paste commands: starting a repository, pushing it to an empty GitHub remote, staging deliberately, committing, working on a feature branch, fixing the last commit, and stopping the tracking of a file that never should have been committed.
Every repository and branch name in this article is a placeholder for teaching. Replace USERNAME/REPO with your own GitHub account and repository name, and keep or rename feature-branch as you like.
Prerequisites
- Git 2.28 or newer installed on your machine. The examples were verified with Git 2.47.3.
- A GitHub account and a freshly created, empty repository. On GitHub choose "New repository", enter a name, and do not add a README, .gitignore or license. The remote must be empty for the first
git pushto succeed, because a push into a non-empty remote that your local branch does not know about is rejected. If the remote already contains commits, clone it first and copy your project files into that clone. Do not try to join unrelated local and remote histories with a routine pull. - A Git identity configured. Once, for all repositories:
bash
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
Or for a single repository, without --global. Commits fail without an identity.
- A local folder where the project lives, and a terminal already inside it.
Initialize the repository and make the first commit
Start in the empty project folder. Create the repository first, then rename its initial branch to main as shown below:
git init
git init creates the .git directory that holds all repository data. Without -b main (the option was added in Git 2.28), the first branch may be named master on older setups. If a repository was already initialized under a different name, rename the current branch instead:
git branch -M main
Create or edit your first files, then inspect what will be staged before adding anything:
git status
git status lists untracked files and modified files. Read it before running git add . so you never stage what you did not intend to, such as local environment files, build output or credentials. If something should never be tracked, add a pattern to .gitignore before staging. Git only ignores files that are not tracked yet, which is why the ignore file comes first.
Then stage and commit:
git add .
git commit -m "initial commit"
git add . stages every change in the current directory tree. git commit writes a snapshot of the staged content, not of the whole working directory. If nothing is staged, the commit is refused.
Connect the GitHub remote
Create the repository on GitHub first (empty, as in the prerequisites). Then add the remote. The command line must be plain shell syntax, with the URL as a single argument:
git remote add origin https://github.com/USERNAME/REPO.git
Two malformed variants you may find in chats or Markdown documents do not identify the intended HTTPS remote:
git remote add origin `https://github.com/USERNAME/REPO.git`
git remote add origin @url:https://github.com/USERNAME/REPO.git
The original supplied form, git remote add origin @url:`https://github.com/USERNAME/REPO.git`, mixes a chat URL wrapper with shell syntax; it is not an executable Git command. The backticks are Markdown code formatting, not part of the command. Pasted into a terminal, the shell would try to interpret them as command substitution, which either errors out or executes whatever the backticks surround. The @url: prefix is not a URL scheme and not a git remote form, so it does not identify the intended GitHub remote even if Git accepts it as a stored string. Use the HTTPS command above instead, with your own owner and repository, and verify it:
git remote -v
The output lists the same URL for both fetch and push:
origin https://github.com/USERNAME/REPO.git (fetch)
origin https://github.com/USERNAME/REPO.git (push)
Push the first commit and set upstream tracking at the same time:
git push -u origin main
The -u flag (long form --set-upstream) records that local main tracks origin/main. With standard Git configuration, a bare git push and a bare git pull on that branch know where to go without extra arguments. HTTPS authentication also needs to be configured: use GitHub CLI, a credential manager or a personal access token when prompted, never an account password or a token pasted into the URL. Verify the tracking relationship:
git branch -vv
The main line shows [origin/main] next to the latest commit.
Stage changes deliberately
Before each commit, look at what changed:
git status
git diff
git diff shows unstaged changes against the index, and git diff --cached shows staged changes against the last commit. Three staging modes cover most of the work:
git add .
Stage every change in the tree: new files, modifications and deletions.
git add path/to/file # Replace this with a real file path
Stage only the named path and leave the rest of the changes unstaged.
git add -p
Interactive patch mode. Git walks through each hunk of the diff and asks whether to stage it. Answer y to stage, n to skip, and s to split a hunk into smaller pieces when possible. This is how you commit part of a file and keep the remaining changes for a later commit.
A typical change on top of a compose rebuild, with its docs, looks like this:
git add docker-compose.yml docs/
git commit -m "Add docker compose rebuild docs"
Never stage secrets
Put the likely offenders in .gitignore before the first git add .. A Docker based project typically ignores:
.env
*.log
__pycache__/
db.sqlite3
git status and git diff --cached before every commit are the last two checks: whatever is in the index goes into the next commit. If a secret still ends up committed, it is now part of history. Deleting the secret from the file and committing the deletion does not remove the earlier commits, so rotate the credential and treat the history as exposed (see the section below on stopping tracking).
Pull with rebase
When the remote received new commits, for example from another machine or a collaborator, with a clean working tree and while on local main, update it with:
git pull --rebase origin main
This fetches the remote branch and replays your local commits on top of the fetched remote tip, instead of creating a merge commit. The history stays a single line, which keeps git log readable in a small project.
If the same lines changed on both sides, the rebase stops with a conflict. Fix the conflicted files in your working tree, stage the resolution, then continue:
git add path/to/resolved-file
git rebase --continue
Once the rebase finishes, run git push. Rebase rewrites replayed commits, so avoid rebasing commits others already depend on. Or give up on the whole rebase and return to the exact state from before:
git rebase --abort
Work on a feature branch
Branches are cheap pointers, so cut one before trying anything new and keep main clean:
git checkout -b feature-branch
This creates feature-branch from the current commit and switches to it. Make your changes, then stage and commit as usual:
git add .
git commit -m "feature work"
The generic form is git push -u origin <branch-name>; replace <branch-name> before running it. For this example, publish the branch on the first push with:
git push -u origin feature-branch
From then on, a bare git push while on feature-branch sends new commits to origin/feature-branch. When the work is done, merge it back or open a pull request, and clean up the local branch with git branch -d feature-branch once it is merged.
Fix the last commit: amend
You committed, and then noticed that a file was missing from that commit. As long as the commit exists only on your machine and was never pushed, fold the file in with:
git add forgotten-file
git commit --amend --no-edit
--amend replaces the last commit with a new one that also contains the newly staged file, and --no-edit keeps the original message so no editor opens. The commit hash changes because the content changed. That is exactly why this is only safe for commits nobody else has pulled:
- Never amend a commit that was already pushed to a branch other people share.
- If you amended a pushed commit on a branch that only you use, coordinate with anyone who has that branch, then update the remote with a force push that still checks first:
git push --force-with-lease
This bare form assumes the current branch is your own feature-branch with its upstream configured. To name the target explicitly, use git push --force-with-lease origin feature-branch.
--force-with-lease overwrites the remote branch only if it still matches the state you last fetched. If someone pushed to that branch in the meantime, the push is refused instead of silently deleting their work. That check is what separates it from a plain --force. Use it only on your own rewritten feature branch that you are coordinating, never on a shared main. On shared main, undo mistakes with git revert, which creates a new commit instead of rewriting history.
Stop tracking a file that should not be in Git
Say a document, your-file.pdf, was committed by mistake. Remove it from Git's index while keeping the file on your disk:
git rm --cached your-file.pdf
Then append the ignore rule without overwriting existing rules (>> appends; > would replace the file):
echo "your-file.pdf" >> .gitignore
Important: stage and commit the .gitignore together with the removal, and only then push. If you skip committing the ignore file, the next git add . stages the PDF again and the mistake repeats:
git add .gitignore
git commit -m "Stop tracking PDF and add to gitignore"
git push
Two honest limits of this approach:
- Removing tracking does not erase history.
your-file.pdfis still present in the earlier commits and can still be downloaded from the remote. If the file contains anything sensitive, treat it as leaked: rotate what it protects, and consider rewriting history with a dedicated tool before other people clone the repository. .gitignoreonly affects untracked files. It cannot untrack something by itself. Thegit rm --cachedstep is what removes the file from the index.
Verify the new state:
git status
git check-ignore -v your-file.pdf
check-ignore -v prints the matching pattern and the file that defines it, confirming the rule is active.
Everyday inspection and recovery tips
A short reference for the moments when something feels off:
git status
git status -sb
Full working tree state, and the compact short plus branch format, which is the fastest daily check.
git diff
git diff --cached
git diff main..feature-branch --stat
Unstaged changes, staged changes, and a per-file summary of the difference between two branches.
git log --oneline
git log --oneline --graph --all
git log -5
One line per commit, an ASCII graph of all branches, and the last five commits.
git stash push -m "wip compose tweaks"
git stash list
git stash pop
Park uncommitted tracked changes under a message, list the stashes, and reapply the most recent one, dropping it only if application succeeds. Conflicts leave the stash available. Stashing covers tracked changes by default; add -u to include untracked files.
git revert --no-edit HEAD
Create a new commit that undoes the last one, without touching history. This is the safe undo on shared branches.
git rebase --abort
git rebase --continue
git rebase --skip
After a rebase stops on a conflict: give up and restore the pre-rebase state, finish the rebase after resolving, or drop the commit that caused the conflict.
Check the result
After the full cycle, these should all hold:
git branch -vvshowsmaintrackingorigin/mainwith no ahead or behind count.git statusis clean, or lists only files you intentionally left untracked.git remote -vshows the HTTPS URL for both fetch and push.git check-ignore -v your-file.pdfprints the matching pattern, andgit statusno longer lists the PDF.- On GitHub, the repository shows the pushed commits on
mainand, if you pushed the feature branch, onfeature-branchtoo.
Do not treat a push without errors as proof that the right content landed. Open the commit on GitHub and compare its file list with git show --stat HEAD from your machine.
The whole cycle as one map
Each command from this guide, as one interactive map. Select a command to see which of the five areas it touches and in which direction it moves your work.
The full-screen version with the complete desktop layout: open the standalone map.
Limitations and references
- Command syntax was verified against the official Git documentation (git-scm.com) and the Git 2.47.3 man pages. Older versions may lack
git init -b(added in Git 2.28) and some--force-with-leaseforms. - All repository, branch and file names in the examples are placeholders, and the examples were exercised only in disposable local repositories with a local bare remote, never against a production repository or GitHub account.
- Official documentation: git-push, git-add, git-commit, git-branch, git-rebase, git-rm, gitignore, Everyday Git, the Pro Git book, and Creating a new repository in GitHub Docs.