Git Branches: Create, Switch, Rename and Delete Branches

Branches let you work on features and fixes without breaking stable code. In this lesson you will create, switch, push, rename and delete branches, understand HEAD, and adopt naming conventions used by professional teams.

πŸ“– What You’ll Learn: what branches and HEAD are, listing branches, creating and switching with git switch and git checkout, working and committing on a branch, pushing branches, renaming and deleting branches locally and on GitHub, and branch naming conventions.


🌿 What Is a Branch?

A branch is an independent line of work. You create one to build a feature, fix a bug or try an idea without touching the stable code on main. When the work is ready, you merge it back.

Technically a branch is just a lightweight, movable pointer to a commit. Creating one is instant, even in huge repositories, which is why Git users branch all the time.

                 C4 ── C5      ← feature/login-tests
                /
C1 ── C2 ── C3                 ← main
                       ↑
                     HEAD points to the branch you are on

HEAD is Git’s marker for “where you are now”, usually the current branch.


πŸ“‹ List Branches

git branch          # local branches; * marks the current one
git branch -a       # local and remote-tracking branches
git branch -v       # with the latest commit of each
git branch -vv      # plus upstream and ahead/behind information
  feature/login-tests
* main

βž• Create and Switch Branches

Modern Git (2.23 and newer) has git switch, made just for branches:

git switch -c feature/login-tests     # create a branch and switch to it
git switch main                       # switch to an existing branch
git switch -                          # switch back to the previous branch

The older, still common equivalents use git checkout:

TaskModernOlder
Create and switchgit switch -c namegit checkout -b name
Switchgit switch namegit checkout name
Create without switchinggit branch namegit branch name
Branch from a specific commit or branchgit switch -c hotfix maingit checkout -b hotfix main

πŸ’‘ Tip: Commit (or stash) your changes before switching branches. Git refuses to switch if your uncommitted changes would be overwritten.


πŸ§ͺ Work on a Branch

git switch -c feature/login-tests
# edit tests/login.spec.ts
git add tests/login.spec.ts
git commit -m "Add login tests for locked-out users"
git log --oneline --graph --all
* 7e2f1a9 (HEAD -> feature/login-tests) Add login tests for locked-out users
* 8b1d4e2 (origin/main, main) Add learning goals and initial test plan
* 3f2a91c Add README with project title

main has not moved; your new commit exists only on the feature branch.


☁️ Push a Branch to GitHub

git push -u origin feature/login-tests

GitHub then shows a Compare & pull request button. Opening a pull request is covered in Pull Requests Step by Step.

Work on a teammate’s branch:

git fetch
git switch feature/api-tests      # creates a local branch tracking origin/feature/api-tests

✏️ Rename a Branch

git branch -m new-name                 # rename the current branch
git branch -m old-name new-name        # rename another branch

Rename a branch that is already on GitHub:

git branch -m feature/login feature/login-tests
git push origin -u feature/login-tests       # push the new name
git push origin --delete feature/login       # delete the old name on GitHub

πŸ—‘οΈ Delete a Branch

git branch -d feature/login-tests      # delete if already merged (safe)
git branch -D experiment               # force delete, even if not merged
git push origin --delete feature/login-tests   # delete the branch on GitHub
git fetch --prune                      # clean up remote-tracking branches deleted on GitHub

⚠️ Common mistake: git branch -D deletes unmerged work. If you deleted the wrong branch, find its last commit with git reflog and recreate it with git branch name <hash>.


🏷️ Branch Naming Conventions

Clear names make a repository easy to navigate. A common convention:

PrefixUseExample
feature/New functionality or testsfeature/checkout-api-tests
bugfix/ or fix/Bug fixesbugfix/flaky-login-wait
hotfix/Urgent production fixeshotfix/payment-timeout
chore/Maintenance, dependencies, configchore/upgrade-playwright
docs/Documentationdocs/readme-setup
release/Release preparation (Git Flow)release/2.4.0

Use lowercase, hyphens instead of spaces, and add a ticket number if your team uses one: feature/QA-123-login-tests. Strategies such as Git Flow and trunk-based development are in branching strategies.


πŸ“ Assignment

  1. In git-practice, create feature/notes with git switch -c, make two commits, and view the graph with git log --oneline --graph --all.
  2. Switch back to main and confirm the new commits are not there.
  3. Push the branch to GitHub with -u and find it in the branch dropdown on GitHub.
  4. Rename it to feature/study-notes locally and on GitHub.
  5. Create a throwaway branch, commit something, delete it with -D, then recover it with git reflog.
  6. Delete the remote branch and clean up with git fetch --prune.

❓ FAQ

πŸ€” What is a branch in Git?

A movable pointer to a commit that lets you develop independently from other work. New commits on a branch do not affect other branches until you merge.

πŸ€” How do I create a new branch in Git?

git switch -c branch-name (or git checkout -b branch-name) creates it and switches to it.

πŸ€” What is the difference between git switch and git checkout?

git switch is a newer command only for changing branches. git checkout does that and also restores files, which made it confusing; both still work.

πŸ€” How do I delete a branch locally and on GitHub?

git branch -d name locally (or -D to force) and git push origin --delete name on GitHub.

πŸ€” How do I rename a Git branch?

git branch -m new-name for the current branch; for a pushed branch, push the new name and delete the old one on GitHub.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

How to Push an Existing Project to GitHub (Step by Step)

You have a project on your computer and want it on GitHub. This lesson gives you the exact commands for a new or existing Git repository, explains each step, and fixes the errors people hit most often on their first push.

πŸ“– What You’ll Learn: creating an empty GitHub repository, preparing a .gitignore and checking for secrets, init, commit, branch -M main, remote add and push -u, pushing a project that already uses Git, handling a GitHub README with unrelated histories, the gh shortcut, and troubleshooting.


🎯 The Goal

You already have a project on your computer, for example a Playwright test framework or a Python script folder, and you want it on GitHub. This lesson shows the exact steps, for a folder that is not yet a Git repository and for one that already is.


🧭 Step 1: Create an Empty Repository on GitHub

  1. On GitHub, click + (top right), then New repository.
  2. Enter a name (for example playwright-framework), an optional description, and choose Public or Private.
  3. Do not tick “Add a README file”, “.gitignore” or “license”. Your local project will provide these, and an empty repository avoids a conflict on the first push.
  4. Click Create repository and copy the HTTPS or SSH URL shown on the next page.

πŸ“ Step 2: Prepare the Local Project

Open a terminal in your project folder. First add a .gitignore so dependencies, reports and secrets are not uploaded:

node_modules/
test-results/
playwright-report/
.env

⚠️ Common mistake: Check for secrets before the first commit: passwords, API keys, tokens and .env files. Once pushed to a public repository, consider them leaked.


πŸš€ Step 3: Commit and Push (Folder Not Yet Using Git)

git init
git add .
git status                       # check that only the right files are staged
git commit -m "Initial commit: Playwright framework"
git branch -M main               # make sure the branch is called main
git remote add origin git@github.com:asha-verma-qa/playwright-framework.git
git push -u origin main

Refresh the GitHub page: your files and commit are there.

CommandWhy
git initTurns the folder into a repository (first repository)
git add . and git commitCreates the first snapshot
git branch -M mainRenames the current branch to main (some setups default to master)
git remote add origin <url>Connects to the GitHub repository (remotes)
git push -u origin mainUploads and sets upstream tracking (push)

πŸ” Step 3 (Alternative): Folder Already Using Git

If the project already has commits, you only need to add the remote and push:

git remote -v                     # check: is there already an origin?
git remote add origin git@github.com:asha-verma-qa/playwright-framework.git
git push -u origin main

If origin already points somewhere else, change it: git remote set-url origin <new-url>. To push every local branch and tag: git push -u origin --all and git push origin --tags.


⚠️ If You Already Created a README on GitHub

Then GitHub has a commit your local repository does not, and the first push is rejected. Merge the two histories once:

git pull origin main --allow-unrelated-histories
# resolve conflicts if any (often in README.md), then:
git push -u origin main

--allow-unrelated-histories is needed because the two repositories have no common starting commit.


⚑ Shortcut: GitHub CLI

With the GitHub CLI you can create the GitHub repository and push in one command from your project folder:

gh repo create playwright-framework --private --source=. --remote=origin --push

βœ… After the First Push

  • Add a good README with setup and run instructions (Markdown and README).
  • Add a description and topics (for example playwright, typescript, test-automation) on the repository page so people can find it.
  • Add a CI workflow so tests run on every push (Playwright in GitHub Actions).

🐞 Troubleshooting

ErrorFix
error: remote origin already existsUse git remote set-url origin <url> instead of add
src refspec main does not match anyNo commit yet, or the branch is named differently: commit first, or git branch -M main
! [rejected] main -> main (fetch first)GitHub has a README or other commits: use the “unrelated histories” steps above
fatal: refusing to merge unrelated historiesAdd --allow-unrelated-histories to the pull
Huge upload or node_modules on GitHubAdd a .gitignore, run git rm -r --cached node_modules, commit and push

πŸ“ Assignment

  1. Take any existing project folder on your computer (or create one with a few files) and add a .gitignore.
  2. Create an empty repository on GitHub and push the project with the commands in Step 3.
  3. Create a second GitHub repository with a README, then push another local project to it using --allow-unrelated-histories.
  4. Add a description, topics and a README to your repository on GitHub.
  5. Bonus: install the GitHub CLI and create and push a repository with gh repo create.

❓ FAQ

πŸ€” How do I push an existing project to GitHub?

Create an empty repository on GitHub, then in your project folder run git init, git add ., git commit -m "Initial commit", git branch -M main, git remote add origin <url> and git push -u origin main.

πŸ€” Why should I not add a README when creating the GitHub repository?

It creates a commit on GitHub that your local repository does not have, so your first push is rejected until you merge the two histories.

πŸ€” What does git branch -M main do?

It renames the current branch to main, overwriting any existing branch with that name.

πŸ€” How do I fix “remote origin already exists”?

Change the URL with git remote set-url origin <url>, or remove it with git remote remove origin and add it again.

πŸ€” What does –allow-unrelated-histories mean?

It lets Git merge two repositories that do not share a common first commit, such as a local project and a GitHub repository created with a README.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

git fetch vs git pull: Differences, Examples and When to Use Each

git fetch and git pull both get changes from GitHub, but they do very different things to your work. This lesson explains the difference with examples, shows how to review changes before integrating them, and helps you choose between merge and rebase when pulling.

πŸ“– What You’ll Learn: what fetch and pull do, a side-by-side comparison, fetch options and inspecting incoming commits, pull options, merge vs rebase vs fast-forward-only pulls, a safe pre-push workflow, and fixes for common pull messages.


βš–οΈ The Short Answer

  • git fetch downloads new commits and branches from the remote without changing your files or your current branch. It only updates remote-tracking branches such as origin/main.
  • git pull does a fetch and then integrates the new commits into your current branch (with a merge by default, or a rebase).
git pull  =  git fetch  +  git merge   (or git rebase with --rebase)

🧭 Side-by-Side Comparison

git fetchgit pull
Downloads new commitsβœ…βœ…
Updates origin/main and other remote-tracking branchesβœ…βœ…
Changes your current branchβŒβœ…
Changes files in your working directoryβŒβœ…
Can cause merge conflictsβŒβœ…
Safe to run any timeβœ… Always⚠️ Commit or stash your work first
Best forSeeing what changed before integratingQuickly updating your branch

πŸ” git fetch in Practice

git fetch                 # fetch from origin
git fetch --all           # fetch from every remote
git fetch --prune         # also remove remote-tracking branches deleted on GitHub
git fetch upstream        # fetch from another remote, e.g. the original project of a fork

After fetching, inspect the incoming changes before they touch your work:

git status
# Your branch is behind 'origin/main' by 3 commits, and can be fast-forwarded.

git log --oneline main..origin/main     # commits on GitHub that you do not have
git log --oneline origin/main..main     # your commits that GitHub does not have
git diff main origin/main               # the actual changes

Then integrate when you are ready:

git merge origin/main      # or: git rebase origin/main

πŸ’‘ Tip: git fetch is completely safe. Many experienced developers fetch often and pull deliberately, because fetch lets them review incoming work first.


πŸ“₯ git pull in Practice

git pull                   # fetch + merge the upstream of the current branch
git pull origin main       # fetch main from origin and merge it into the current branch
git pull --rebase          # fetch + rebase your local commits on top
git pull --ff-only        # only update if no merge is needed; otherwise stop

Merge or rebase when pulling?

StrategyCommand or settingResult when both sides have new commits
Merge (default)git config --global pull.rebase falseA merge commit joins the two histories
Rebasegit config --global pull.rebase trueYour local commits are replayed on top; history stays linear
Fast-forward onlygit config --global pull.ff onlyPull refuses and you decide what to do

If neither is configured, recent Git versions show a hint asking you to choose; that is why the config lesson sets pull.rebase false. Many teams prefer --rebase for feature branches to avoid “Merge branch ‘main’ of github.com…” commits. See rebase vs merge.


πŸ§ͺ A Safe Workflow Before Pushing

git status                     # 1. make sure your work is committed (or stashed)
git fetch                      # 2. see what changed on GitHub
git log --oneline main..origin/main
git pull --rebase              # 3. integrate (resolve conflicts if needed)
npx playwright test            # 4. run your tests on the combined code
git push                       # 5. share

Unfinished work? Save it temporarily with git stash before pulling.


🐞 Common Situations

MessageMeaning and fix
“Your branch is behind ‘origin/main’ by 3 commits, and can be fast-forwarded”Only GitHub has new commits; git pull will fast-forward cleanly
“Your branch and ‘origin/main’ have diverged”Both sides have new commits; pull with merge or rebase
“Your local changes would be overwritten by merge”Commit or stash your changes, then pull
“Automatic merge failed; fix conflicts”Resolve the merge conflicts, then commit
Deleted remote branches still listedgit fetch --prune (or set fetch.prune true)

πŸ“ Assignment

Use two clones of the same GitHub repository (practice and practice-copy):

  1. Commit and push a change from practice-copy.
  2. In practice, run git fetch and git status. Confirm your files did not change.
  3. Use git log main..origin/main and git diff main origin/main to inspect the incoming change, then git merge origin/main.
  4. Create diverging commits in both clones and pull once with merge and once with --rebase. Compare the histories with git log --oneline --graph.
  5. Delete a branch on GitHub and remove its remote-tracking branch with git fetch --prune.

❓ FAQ

πŸ€” What is the difference between git fetch and git pull?

git fetch only downloads new commits and updates remote-tracking branches. git pull downloads them and also merges (or rebases) them into your current branch.

πŸ€” Is git fetch safe?

Yes. It never changes your working files or your current branch, so it is always safe to run.

πŸ€” When should I use git pull –rebase?

When you want a linear history without extra merge commits, for example on your own feature branch. Avoid rebasing commits others have already based work on.

πŸ€” How do I see what changes will come with git pull?

Run git fetch, then git log main..origin/main for the commits and git diff main origin/main for the changes.

πŸ€” How do I fix “Your branch and origin/main have diverged”?

Run git pull (merge) or git pull --rebase, resolve any conflicts, then push.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

git clone, git push and git pull Explained Step by Step

Clone, push and pull are how you share work through GitHub. In this lesson you will clone repositories, push your commits with upstream tracking, pull your team’s changes, handle rejected pushes and use force-push safely.

πŸ“– What You’ll Learn: git clone and its options, the first push with -u, plain git push, rejected pushes, –force vs –force-with-lease, git pull and pull –rebase, a daily team routine, and common clone, push and pull errors.


πŸ” The Three Commands That Connect You to GitHub

CommandDirectionWhat it does
git cloneGitHub β†’ your computer (once)Downloads a full copy of a repository, with its history
git pushYour computer β†’ GitHubUploads your new commits
git pullGitHub β†’ your computerDownloads new commits and merges them into your branch

πŸ“₯ git clone: Get a Copy of a Repository

On any GitHub repository page, click the green Code button and copy the HTTPS or SSH URL:

git clone git@github.com:microsoft/playwright.git
git clone https://github.com/asha-verma-qa/git-practice.git my-practice   # into a custom folder name
Cloning into 'git-practice'...
remote: Enumerating objects: 15, done.
Receiving objects: 100% (15/15), done.

What you get:

  • A new folder with all files of the default branch.
  • The complete history (git log works offline).
  • A remote called origin pointing to the URL (remotes).
  • A local main branch that tracks origin/main.

Useful clone options

CommandUse
git clone --branch develop <url>Check out a specific branch after cloning
git clone --depth 1 <url>Shallow clone: only the latest snapshot (fast for CI and huge repos)
git clone --recurse-submodules <url>Also clone submodules

πŸ“€ git push: Send Your Commits to GitHub

First push of a branch

git push -u origin main
Enumerating objects: 6, done.
Writing objects: 100% (6/6), 512 bytes | 512.00 KiB/s, done.
To github.com:asha-verma-qa/git-practice.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

-u (--set-upstream) links your local main to origin/main. After that, a plain command is enough:

git push

πŸ’‘ Tip: With git config --global push.autoSetupRemote true (from Configure Git), the first git push of any new branch sets the upstream automatically.

When push is rejected

! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'github.com:asha-verma-qa/git-practice.git'
hint: Updates were rejected because the remote contains work that you do not have locally.

Someone else pushed first. Get their commits, then push again:

git pull
git push

Force push (use with care)

After rewriting history (for example a rebase), a normal push is rejected. Prefer the safer form:

git push --force-with-lease

--force-with-lease refuses to overwrite the remote if someone else pushed commits you have not seen. Plain --force overwrites blindly.

⚠️ Common mistake: Never force-push to shared branches such as main or develop. It can delete teammates’ work. Many teams block it with branch protection.


πŸ“₯ git pull: Get Your Team’s Changes

git pull
Updating 8b1d4e2..c4d5e6f
Fast-forward
 tests/login.spec.ts | 12 ++++++++++++
 1 file changed, 12 insertions(+)

git pull is two commands in one: git fetch (download) and git merge (integrate). If you and a teammate changed the same lines, you get a merge conflict. The difference between fetch and pull has its own lesson.

git pull origin main        # pull a specific branch from a specific remote
git pull --rebase           # replay your local commits on top instead of merging

πŸ”„ A Daily Team Routine

git pull                          # 1. start the day up to date
# ... edit files ...
git add .
git commit -m "Add API tests for orders endpoint"   # 2. commit small changes often
git pull                          # 3. integrate teammates' work before pushing
git push                          # 4. share your work

In real teams you push to a feature branch and open a pull request instead of pushing to main directly. Branches are next in Module 4.


🐞 Common Errors

ErrorFix
fatal: repository not foundWrong URL or no access; check git remote -v and your GitHub permissions
Permission denied (publickey)SSH key not set up; see SSH keys or use HTTPS
Authentication failed (HTTPS)Passwords are not accepted; use Git Credential Manager or a personal access token
rejected (fetch first)Run git pull, resolve any conflicts, then push
There is no tracking information for the current branchPush once with git push -u origin <branch>

πŸ“ Assignment

  1. Push your local git-practice repository to GitHub with git push -u origin main and refresh the GitHub page.
  2. Clone the same repository into another folder (git clone <url> practice-copy).
  3. In the copy, make a commit and push it. In the original folder, run git pull and check git log --oneline.
  4. Make commits in both folders, push from one, and push from the other to see the “rejected” message. Fix it with git pull and push again.
  5. Clone a popular open-source repository with --depth 1 and compare its size with a full clone.

❓ FAQ

πŸ€” How do I push code to GitHub?

Commit your changes, then run git push. For the first push of a branch use git push -u origin <branch> to set the upstream.

πŸ€” What does git push -u origin main mean?

Push the local main branch to the remote origin and remember origin/main as its upstream, so later you can just run git push and git pull.

πŸ€” What is the difference between git clone and git pull?

git clone creates a new local copy of a repository once. git pull updates an existing local copy with new commits from the remote.

πŸ€” Why is my git push rejected?

The remote has commits you do not have. Run git pull, resolve conflicts if any, then push again.

πŸ€” What is the difference between –force and –force-with-lease?

--force overwrites the remote branch unconditionally. --force-with-lease only overwrites it if nobody else has pushed in the meantime, which is much safer.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Git Remote Explained: origin, upstream and Remote-Tracking Branches

A remote connects your local repository to a copy on GitHub. In this lesson you will add and manage remotes, understand origin and upstream, and read remote-tracking branches such as origin/main so push and pull make sense.

πŸ“– What You’ll Learn: what remotes are, origin vs upstream, listing, adding, changing, renaming and removing remotes, inspecting a remote, remote-tracking branches, ahead and behind, upstream tracking, and remotes in a fork workflow.


🌐 What Is a Remote?

So far your repository lives only on your computer. A remote is another copy of the same repository, usually on a server such as GitHub, that you can send commits to and receive commits from. Remotes are how teams share work and how your code is backed up.

A local repository can have several remotes. Each has a short name and a URL.

NamePoints toTypical use
originThe repository you cloned from, or your main GitHub repositoryPush and pull your work
upstreamThe original project you forkedGet updates from the original project (forks)

origin and upstream are only conventions; you could name a remote anything.


πŸ‘€ List Your Remotes

git remote          # names only
git remote -v       # names and URLs
origin  git@github.com:asha-verma-qa/git-practice.git (fetch)
origin  git@github.com:asha-verma-qa/git-practice.git (push)

A repository created with git init has no remotes. A cloned repository automatically has origin.


βž• Add a Remote

Create an empty repository on GitHub (no README, .gitignore or licence), copy its URL, then:

git remote add origin git@github.com:asha-verma-qa/git-practice.git
git remote -v

Use the HTTPS URL (https://github.com/...) if you have not set up SSH keys.


✏️ Change, Rename or Remove a Remote

git remote set-url origin https://github.com/asha-verma-qa/git-practice.git   # switch SSH to HTTPS (or the reverse)
git remote rename origin github
git remote remove github

Changing the URL is common when a repository is renamed or moved to another organization, or when you switch between HTTPS and SSH.


πŸ”Ž Inspect a Remote

git remote show origin
* remote origin
  Fetch URL: git@github.com:asha-verma-qa/git-practice.git
  Push  URL: git@github.com:asha-verma-qa/git-practice.git
  HEAD branch: main
  Remote branches:
    main tracked
  Local branch configured for 'git pull':
    main merges with remote main
  Local ref configured for 'git push':
    main pushes to main (up to date)

🌿 Remote-Tracking Branches

When Git talks to a remote, it remembers the remote’s branches locally as remote-tracking branches, named origin/main, origin/feature-login and so on. They are read-only bookmarks of “where the remote was the last time I checked”.

git branch -r      # remote-tracking branches
git branch -a      # local and remote-tracking branches
git branch -vv     # local branches with their upstream and ahead/behind counts
* main 8b1d4e2 [origin/main: ahead 2] Add learning goals and initial test plan

“Ahead 2” means you have two local commits that are not on GitHub yet. “Behind 3” would mean GitHub has three commits you have not pulled.

Upstream (tracking) branch

A local branch can track a remote branch, its upstream. Then plain git push and git pull know where to go. You set it with git push -u (next lesson) or manually:

git branch --set-upstream-to=origin/main main

🍴 origin and upstream with Forks

When you contribute to someone else’s project, you usually fork it on GitHub and clone your fork:

git clone git@github.com:asha-verma-qa/playwright-demo.git     # your fork = origin
cd playwright-demo
git remote add upstream https://github.com/original-org/playwright-demo.git
git fetch upstream                                             # get the original project's updates

The full fork workflow is in Fork a Repository and Contribute to Open Source.


πŸ“ Assignment

  1. Create an empty git-practice repository on GitHub and add it as origin to your local git-practice repository.
  2. Run git remote -v and git remote show origin (after the first push in the next lesson).
  3. Switch the remote URL from SSH to HTTPS and back with git remote set-url.
  4. Rename origin to github and back.
  5. Run git branch -vv before and after making a local commit and explain “ahead”.

❓ FAQ

πŸ€” What is origin in Git?

The default name for the remote repository you cloned from or added first, usually your repository on GitHub.

πŸ€” What is the difference between origin and upstream?

origin is usually your own copy (often a fork). upstream is the original project you forked from, used to bring its latest changes into your fork.

πŸ€” How do I change the remote URL in Git?

git remote set-url origin <new-url>, then check with git remote -v.

πŸ€” What is origin/main?

A remote-tracking branch: Git’s local record of where main was on origin the last time you fetched or pulled.

πŸ€” How do I see all branches including remote ones?

git branch -a lists local and remote-tracking branches.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Undo Changes in Git: restore, reset, revert and amend Explained

Everyone makes mistakes in Git. The trick is knowing which undo command fits the situation. This lesson gives you a decision table and explains git restore, commit –amend, the three modes of git reset, git revert, git clean and the reflog safety net.

πŸ“– What You’ll Learn: a quick decision table, discarding and unstaging changes with git restore, fixing the last commit with –amend, git reset –soft, –mixed and –hard, git revert for pushed commits, reset vs revert, git clean, and recovering with git reflog.


↩️ Mistakes Happen: Git Can Undo Almost Anything

Edited the wrong file? Committed too early? Pushed a bug? Git has a precise command for each situation. The key question is always: where is the change now? In the working directory, the staging area, a local commit, or a commit already pushed to GitHub?

Review the three areas in Working Directory, Staging Area and Repository if needed.


🧭 Quick Decision Table

SituationCommandSafe?
Discard unsaved edits in a filegit restore file⚠️ Edits are lost
Unstage a file (keep the edits)git restore --staged fileβœ…
Fix the last commit’s messagegit commit --amend -m "new message"βœ… if not pushed
Add a forgotten file to the last commitgit add file then git commit --amend --no-editβœ… if not pushed
Undo the last commit, keep changes stagedgit reset --soft HEAD~1βœ… if not pushed
Undo the last commit, keep changes unstagedgit reset HEAD~1 (mixed)βœ… if not pushed
Throw away the last commit and its changesgit reset --hard HEAD~1⚠️ Changes are lost
Undo a commit that is already pushedgit revert <hash>βœ… Always safe
Delete untracked filesgit clean -n (preview), then git clean -fd⚠️ Files are lost

πŸ“ 1. Discard Changes in the Working Directory: git restore

git restore test-plan.txt     # discard edits in one file
git restore .                 # discard all unstaged edits

This replaces the file with the version from the staging area (or the last commit). Older tutorials use git checkout -- file, which does the same thing.

⚠️ Common mistake: Discarded edits were never committed, so Git cannot bring them back. Run git diff file first to be sure.


πŸŽ’ 2. Unstage Changes: git restore –staged

git add .
git restore --staged secrets.txt   # remove it from the next commit, keep the file as it is

The older equivalent is git reset HEAD secrets.txt.


✏️ 3. Fix the Last Commit: git commit –amend

Typo in the message:

git commit --amend -m "Add login tests for locked-out users"

Forgot a file:

git add tests/logout.spec.ts
git commit --amend --no-edit

--amend replaces the last commit with a new one (new hash). Use it only for commits you have not pushed yet.


βͺ 4. Undo Local Commits: git reset

git reset moves your branch back to an earlier commit. The three modes decide what happens to the changes from the removed commits:

ModeBranch moves backStaging areaWorking directoryUse it to
--softβœ…Changes kept stagedUnchangedRedo the commit, e.g. combine several commits
--mixed (default)βœ…Changes unstagedUnchangedRe-select what to commit
--hardβœ…ResetChanges deletedThrow work away completely
git log --oneline
# 9c7e1aa (HEAD -> main) WIP debug logs
# 8b1d4e2 Add learning goals and initial test plan
# 3f2a91c Add README with project title

git reset --soft HEAD~1    # undo "WIP debug logs", changes stay staged
git reset HEAD~1           # same, but changes become unstaged
git reset --hard HEAD~1    # undo it and delete its changes
git reset --hard 3f2a91c   # go back to a specific commit

⚠️ Common mistake: Never use git reset on commits that are already pushed to a shared branch. It rewrites history, and teammates who pulled those commits will end up with conflicts. Use git revert instead.


πŸ”„ 5. Undo Pushed Commits Safely: git revert

git revert does not delete anything. It creates a new commit that applies the opposite changes, so history stays intact and everyone can simply pull it:

git revert 9c7e1aa
# Git opens the editor with the message "Revert "WIP debug logs"". Save and close.
git push
a1b2c3d (HEAD -> main) Revert "WIP debug logs"
9c7e1aa WIP debug logs
8b1d4e2 Add learning goals and initial test plan
git resetgit revert
How it undoesMoves the branch back; removes commits from historyAdds a new commit with the inverse changes
HistoryRewrittenPreserved
Safe for pushed or shared branches❌ Noβœ… Yes
Typical useClean up local work before pushingUndo a change that is already on GitHub

Useful options: git revert --no-edit <hash> (keep the default message) and git revert HEAD~3..HEAD (revert a range of commits).


🧹 6. Remove Untracked Files: git clean

git clean -n     # dry run: list what would be deleted
git clean -f     # delete untracked files
git clean -fd    # also delete untracked folders

Files listed in .gitignore are kept unless you add -x.


πŸ›Ÿ The Safety Net: git reflog

Ran git reset --hard by mistake? Commits are not gone immediately. git reflog lists every position HEAD has been in:

git reflog
# 8b1d4e2 HEAD@{0}: reset: moving to HEAD~1
# 9c7e1aa HEAD@{1}: commit: WIP debug logs

git reset --hard 9c7e1aa   # bring the "lost" commit back

Learn more in git reflog: recover lost commits.


πŸ“ Assignment

In your git-practice repository:

  1. Edit a file and discard the edit with git restore.
  2. Stage two files and unstage one with git restore --staged.
  3. Make a commit with a typo in the message and fix it with --amend.
  4. Make a commit, forget a file, and add it with --amend --no-edit.
  5. Make three test commits and try reset --soft, reset --mixed and reset --hard on them, noting what happens to the changes each time.
  6. Make a commit, then undo it with git revert and explain how the history differs from a reset.
  7. Use git reflog to recover a commit you removed with reset --hard.

❓ FAQ

πŸ€” What is the difference between git reset and git revert?

git reset moves the branch back and removes commits from history, which is fine for local work. git revert adds a new commit that undoes a previous one, which is safe for commits already pushed.

πŸ€” How do I undo the last commit but keep my changes?

git reset --soft HEAD~1 keeps them staged; git reset HEAD~1 keeps them unstaged in your files.

πŸ€” How do I undo git add?

git restore --staged <file> (or git reset HEAD <file> in older Git versions).

πŸ€” What does git reset –hard do?

It moves the branch to the given commit and deletes all uncommitted changes and the removed commits’ changes from your files. Use it with care.

πŸ€” How do I undo a commit that I already pushed?

Use git revert <commit-hash> and push the new revert commit. Avoid resetting and force-pushing shared branches.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

.gitignore Explained: Ignore Files in Git the Right Way (with Templates)

Some files should never be in Git: dependencies, test reports, logs and especially secrets. In this lesson you will write a proper .gitignore, understand its pattern syntax, use ready-made templates and fix the classic “.gitignore is not working” problem.

πŸ“– What You’ll Learn: what .gitignore does, what to ignore, creating and committing a .gitignore, pattern syntax and negation, templates for Node, Python and Playwright, untracking already committed files, check-ignore, and personal and global ignore rules.


πŸ™ˆ What Is .gitignore?

Not every file in your project folder belongs in Git. Dependencies, build output, logs, test reports and secrets should stay out of the repository. A .gitignore file is a plain text file, usually in the repository root, that lists patterns of files and folders Git should ignore.

Ignored files do not show up as “untracked” in git status, and git add . skips them.


🚫 What Should You Ignore?

CategoryExamplesWhy
Dependenciesnode_modules/, venv/, .venv/Huge, and recreated with npm install or pip install
Build outputdist/, build/, target/, *.classGenerated from source code
Test results and reportstest-results/, playwright-report/, allure-results/, coverage/Generated on every run
Secrets.env, *.pem, credentials.json, playwright/.auth/Must never be shared publicly
Logs and temp files*.log, *.tmp, .cache/Noise
OS and editor files.DS_Store, Thumbs.db, .idea/, .vscode/ (optional)Personal, not project files

✍️ Create Your First .gitignore

In the repository root:

# Dependencies
node_modules/

# Environment variables and secrets
.env
.env.*
!.env.example

# Test output
test-results/
playwright-report/
allure-results/

# Logs
*.log

# OS files
.DS_Store
Thumbs.db

Commit the .gitignore file itself so the whole team shares the same rules:

git add .gitignore
git commit -m "Add .gitignore for dependencies, secrets and test output"

🧩 Pattern Syntax

PatternMatches
debug.logA file named debug.log in any folder
*.logAny file ending in .log
build/Any folder named build (and everything inside)
/build/Only the build folder in the repository root
docs/*.pdfPDFs directly inside docs, not in its subfolders
docs/**/*.pdfPDFs anywhere inside docs
**/tempA temp file or folder at any depth
!important.logException: do not ignore this file (negation)
# commentA comment line

⚠️ Common mistake: A negation (!file) cannot re-include a file if its parent folder is ignored. Ignore the folder’s contents (logs/*) instead of the folder itself (logs/) when you need exceptions.


🧰 Ready-Made Templates

You rarely write a .gitignore from scratch:

  • When creating a repository on GitHub, choose a template from the Add .gitignore dropdown (Node, Python, Java, VisualStudio and many more).
  • GitHub maintains the official collection in the github/gitignore repository.
  • Generator websites such as gitignore.io combine templates for your language, framework and editor.

Example: Playwright with TypeScript project

node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
.env

This matches what npm init playwright@latest generates, plus the folders for saved login sessions and secrets. See Install Playwright.

Example: Python project

__pycache__/
*.py[cod]
.venv/
venv/
.pytest_cache/
.env
reports/

🧹 Ignoring a File That Is Already Tracked

Adding a file to .gitignore does not affect files Git already tracks. Stop tracking it first:

git rm --cached .env                 # stop tracking, keep the file on disk
git rm -r --cached node_modules      # a whole folder
git commit -m "Stop tracking .env and node_modules"

⚠️ Common mistake: If you committed a secret (password, token, API key) and pushed it, removing it from the latest commit is not enough: it is still in the history. Revoke and rotate the secret immediately, then clean history if needed. GitHub’s secret scanning can detect many leaked tokens: see Secrets, Dependabot and code scanning.


πŸ”Ž Debugging: Why Is (or Isn’t) a File Ignored?

git check-ignore -v playwright-report/index.html
.gitignore:3:/playwright-report/	playwright-report/index.html

The output shows which file and line caused the match. List everything currently ignored with git status --ignored.


🌍 Personal Ignore Rules

Rules that only matter to you (your editor or OS) can live outside the project:

LocationScope
.gitignore in the repoEveryone working on the project (committed)
.git/info/excludeOnly this repository on your computer (not committed)
Global file, set with git config --global core.excludesFile ~/.gitignore_globalAll repositories on your computer

πŸ“ Assignment

  1. In git-practice, create node_modules/test.js, app.log, .env and report/index.html, and check git status.
  2. Write a .gitignore that ignores all four, commit it, and check git status again.
  3. Add !keep.log as an exception and confirm with git check-ignore -v.
  4. Commit a file called secret.txt, then stop tracking it with git rm --cached and ignore it.
  5. Set up a global ignore file for your OS and editor files.
  6. Bonus: generate a .gitignore for Node, Python and VS Code from a template and compare it with yours.

❓ FAQ

πŸ€” What is .gitignore in Git?

A text file that lists files and folders Git should not track, such as dependencies, build output, logs and secrets.

πŸ€” Why is .gitignore not working?

Usually because the file is already tracked. Run git rm --cached <file> and commit. Also check the pattern with git check-ignore -v <file>.

πŸ€” Should I commit the .gitignore file?

Yes. Committing it shares the same ignore rules with everyone on the project.

πŸ€” Should I ignore the .env file?

Yes. .env files usually contain secrets. Commit a .env.example with placeholder values instead.

πŸ€” How do I ignore a folder in Git?

Add the folder name with a trailing slash, for example node_modules/, to .gitignore.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

View Git History and Changes: git log, git show, git diff and git blame

Git remembers everything, but only if you know how to ask. In this lesson you will explore history with git log, inspect commits with git show, compare versions with git diff and find who last changed a line with git blame.

πŸ“– What You’ll Learn: git log and its most useful options, custom log formats, git show and commit references like HEAD~1, git diff between commits, files and branches, how to read a diff, git blame, and history on GitHub.


πŸ“œ Why History Matters

Git’s history answers the questions every team asks: What changed? Who changed it? When? Why? In this lesson you will learn to read history with git log, inspect a single commit with git show, compare versions with git diff and find who last changed a line with git blame.

Use your git-practice repository from your first repository, with a few commits in it.


πŸ“– git log: The Commit History

git log
commit 8b1d4e2c7a9f0b1e2d3c4b5a69788f7e6d5c4b3a (HEAD -> main)
Author: Asha Verma <asha.verma@example.com>
Date:   Thu Oct 30 10:15:42 2026 +0530

    Add learning goals and initial test plan

commit 3f2a91c...

Each entry shows the full commit hash, author, date and message. Newest commits are at the top. Press q to exit the pager and Space to scroll.

The most useful git log options

CommandShows
git log --onelineOne line per commit: short hash and message
git log --oneline --graph --all --decorateBranches and merges as a text graph
git log -n 5Only the last 5 commits
git log --statFiles changed and lines added/removed per commit
git log -pThe full diff of every commit
git log --author="Asha"Commits by an author
git log --since="2 weeks ago"Commits in a time range (also --until)
git log --grep="login"Commits whose message contains “login”
git log -- tests/login.spec.tsCommits that changed one file
git log -S "waitForTimeout"Commits that added or removed that text

πŸ’‘ Tip: Create the alias git lg from the config lesson: git config --global alias.lg "log --oneline --graph --decorate --all". You will use it constantly once you work with branches.

Custom formats

git log --pretty=format:"%h %an %ar %s"
8b1d4e2 Asha Verma 2 hours ago Add learning goals and initial test plan
3f2a91c Asha Verma 3 hours ago Add README with project title

Common placeholders: %h short hash, %an author name, %ar relative date, %ad date, %s subject.


πŸ” git show: Inspect One Commit

git show 8b1d4e2          # a specific commit (the short hash is enough)
git show HEAD             # the latest commit
git show HEAD~1           # the commit before it
git show HEAD:README.md   # a file's content as it was in that commit
git show --stat HEAD      # only the list of changed files

Referring to commits

ReferenceMeaning
HEADThe commit you are on now
HEAD~1 or HEAD^One commit before HEAD
HEAD~3Three commits before HEAD
mainThe latest commit on the main branch
8b1d4e2A specific commit by its (short) hash

βš–οΈ git diff: Compare Versions

git diff                       # unstaged changes
git diff --staged              # staged changes (what you are about to commit)
git diff HEAD~2 HEAD           # changes between two commits
git diff HEAD~2 -- README.md   # one file only
git diff main feature/login    # two branches
git diff --stat main feature/login   # summary only
git diff --word-diff           # highlight changed words instead of whole lines

Reading a diff

diff --git a/test-plan.txt b/test-plan.txt
index 3b18e51..a5c1966 100644
--- a/test-plan.txt
+++ b/test-plan.txt
@@ -1,2 +1,3 @@
 Smoke tests: login, search, checkout
-API tests: none
+API tests: users, orders
+Visual tests: home page
  • --- is the old version, +++ the new version.
  • @@ -1,2 +1,3 @@ means “from line 1, 2 lines before; from line 1, 3 lines after”.
  • Lines starting with - were removed, + were added, and lines with a space are unchanged context.

πŸ“ Note: The staging-area variants of git diff are explained in Working Directory, Staging Area and Repository.


πŸ•΅οΈ git blame: Who Changed This Line?

git blame tests/login.spec.ts
git blame -L 10,20 tests/login.spec.ts   # only lines 10 to 20
8b1d4e2c (Asha Verma 2026-10-30 10:15:42 +0530 12)   await page.getByRole('button', { name: 'Login' }).click();

Each line shows the commit, author and date of its last change. Despite the name, use it to find context, not to blame people. In VS Code, extensions such as GitLens show this inline, and GitHub shows it with the Blame button on any file.


🌐 History on GitHub

On github.com, every repository has a commits link with the full history, each commit has a diff view, and every file has History and Blame buttons. These are the same commands, with a friendly interface.


πŸ“ Assignment

  1. Run git log, git log --oneline and git log --stat and describe the difference.
  2. Show only commits that changed README.md.
  3. Use git show HEAD~1 and git show HEAD:README.md and explain what each displays.
  4. Compare your first and latest commits with git diff <first-hash> HEAD.
  5. Find the commit that added a specific word with git log -S "word".
  6. Run git blame on a file with several commits.
  7. Bonus: build a custom --pretty=format that shows the date, author and message.

❓ FAQ

πŸ€” How do I see commit history in Git?

Run git log, or git log --oneline for a compact view and git log --oneline --graph --all to include branches.

πŸ€” How do I see the changes in a specific commit?

git show <commit-hash> shows the commit’s message and full diff.

πŸ€” What is the difference between HEAD~1 and HEAD^?

For normal commits they are the same: the parent of HEAD. They differ only for merge commits, where ^2 means the second parent.

πŸ€” How do I compare two branches in Git?

git diff branch1 branch2, or git diff --stat branch1 branch2 for a summary of changed files.

πŸ€” How do I exit git log?

Press q to quit the pager.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Git Working Directory, Staging Area and Repository Explained

Most Git confusion disappears once you understand three places: the working directory, the staging area and the repository. This lesson explains them with diagrams, git status output and the commands that move changes between them.

πŸ“– What You’ll Learn: the three areas of Git, the four file states, reading git status and its short format, git diff vs git diff –staged, moving changes with add, restore, rm and mv, and why the staging area creates cleaner commits.


🧩 The Three Areas of Git

Every Git project has three areas. Understanding them makes every other Git command easier.

AreaAlso calledWhat it holds
Working directoryWorking treeThe files you see and edit in your folder
Staging areaIndexThe changes you have selected for the next commit
RepositoryLocal repo, .gitEvery commit, saved permanently
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  git add   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  git commit  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Working directory β”‚ ─────────▢ β”‚ Staging area β”‚ ───────────▢ β”‚  Repository  β”‚
β”‚  (edit files)     β”‚ ◀───────── β”‚   (index)    β”‚              β”‚   (.git)     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ git restoreβ””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                        --staged

Analogy: packing for a trip. The working directory is your room full of clothes, the staging area is the open suitcase where you put only what you want to take, and a commit closes the suitcase and labels it with the date.


🚦 The Four States of a File

StateMeaningHow it gets there
UntrackedNew file Git has never seenYou create a file
UnmodifiedTracked and identical to the last commitAfter a commit
ModifiedTracked, changed, not stagedYou edit a tracked file
StagedChange selected for the next commitgit add

πŸ”Ž Reading git status

git status
On branch main
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	modified:   README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
	modified:   test-plan.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	login.spec.ts

Three sections, three areas: staged (green), modified but not staged (red), and untracked.

The short format

git status -s
M  README.md
 M test-plan.txt
?? login.spec.ts
CodeMeaning
M in the left columnModified and staged
M in the right columnModified, not staged
MMStaged, then modified again
ANew file, staged
DDeleted
??Untracked

πŸ”¬ See the Differences in Each Area

git diff            # working directory vs staging area (unstaged changes)
git diff --staged   # staging area vs last commit (what will be committed)
git diff HEAD       # working directory vs last commit (everything)

πŸ’‘ Tip: Run git diff --staged right before every commit. It shows exactly what you are about to save and catches debug code, passwords and accidental changes.


πŸ” Moving Changes Between Areas

GoalCommand
Stage a changegit add file
Unstage a change (keep it in the file)git restore --staged file
Discard unstaged changes in a filegit restore file (cannot be undone)
Stop tracking a file but keep it on diskgit rm --cached file
Delete a tracked file and stage the deletiongit rm file
Rename or move a tracked filegit mv old.txt new.txt

⚠️ Common mistake: git restore file throws away your uncommitted edits to that file permanently. Check with git diff file first.

More ways to undo things, including commits, are in Undo Changes.


🎯 Why the Staging Area Is Useful

The staging area lets you build clean, focused commits even when you changed many things at once:

# You fixed a bug AND reformatted some files. Commit them separately:
git add src/checkout.ts
git commit -m "Fix rounding of tax on checkout"

git add .
git commit -m "Format test files with Prettier"

With git add -p you can even stage parts of a file: Git shows each changed block (hunk) and asks y (stage), n (skip), s (split) or q (quit).

Small, focused commits make history readable, code review easier and bugs easier to find with tools like git bisect.


πŸ“ Assignment

In your git-practice repository:

  1. Create a new file, modify a tracked file, and stage only the modified one. Run git status and git status -s and identify each state.
  2. Run git diff, git diff --staged and git diff HEAD and describe what each shows.
  3. Stage a file, then unstage it with git restore --staged.
  4. Make a change you do not want and discard it with git restore.
  5. Rename a file with git mv and commit the rename.
  6. Bonus: change two unrelated lines in one file and commit them separately using git add -p.

❓ FAQ

πŸ€” What is the staging area in Git?

A middle step between your files and the repository where you collect the exact changes for the next commit. It is also called the index.

πŸ€” What is the difference between git diff and git diff –staged?

git diff shows changes not yet staged. git diff --staged shows staged changes that will go into the next commit.

πŸ€” How do I unstage a file in Git?

git restore --staged file moves the change out of the staging area but keeps your edits in the file.

πŸ€” What does ?? mean in git status -s?

The file is untracked: Git has never been told to track it.

πŸ€” How do I stop tracking a file without deleting it?

git rm --cached file, then add it to .gitignore so it is not added again.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

git init, add and commit: Create Your First Git Repository

Time to use Git for real. In this lesson you will turn a folder into a repository and make your first commits, learning the four commands you will use every day: git init, git status, git add and git commit.

πŸ“– What You’ll Learn: git init and the .git folder, reading git status, untracked vs staged files, the ways to use git add, git commit -m and -am, viewing history with git log –oneline, and writing good commit messages.


🎯 What You Will Build

In this lesson you will turn an ordinary folder into a Git repository and save your first snapshots (commits). By the end you will know the four commands you will use every single day: git init, git status, git add and git commit.

Make sure Git is installed and configured with your name and email.


πŸ“ Step 1: Create a Project Folder

mkdir qa-notes
cd qa-notes

🧱 Step 2: Initialize the Repository with git init

git init
Initialized empty Git repository in C:/Users/asha/qa-notes/.git/

git init creates a hidden .git folder. That folder is the repository: it stores every commit, branch and setting. Your files stay where they are; Git simply starts watching the folder.

⚠️ Common mistake: Never delete or edit the .git folder by hand. Deleting it removes the entire history of the project.


πŸ” Step 3: Check the State with git status

git status
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)

git status is your best friend. Run it before and after every command; it tells you exactly what Git sees and usually suggests the next command.


✍️ Step 4: Create a File

Create README.md with any editor, or from the terminal:

echo "# QA Notes" > README.md
git status
On branch main

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	README.md

Untracked means Git sees the file but is not managing it yet.


βž• Step 5: Stage the File with git add

git add README.md
git status
Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
	new file:   README.md

The file is now staged: it is in the list of changes that will go into the next commit. Common ways to stage:

CommandStages
git add README.mdOne file
git add docs/Everything in a folder
git add .All changes in the current folder and below
git add -AAll changes in the whole repository, including deletions
git add -pPieces of files, interactively (great for clean commits)

πŸ’Ύ Step 6: Save a Snapshot with git commit

git commit -m "Add README with project title"
[main (root-commit) 3f2a91c] Add README with project title
 1 file changed, 1 insertion(+)
 create mode 100644 README.md

You just made your first commit. 3f2a91c is the start of the commit’s unique ID (hash). Run git status again and you will see “nothing to commit, working tree clean”.


πŸ” Step 7: The Everyday Loop

Make a second change and commit it:

echo "- Learn Git basics" >> README.md
echo "Smoke tests: login, search, checkout" > test-plan.txt
git status
git add README.md test-plan.txt
git commit -m "Add learning goals and initial test plan"

See your history:

git log --oneline
8b1d4e2 (HEAD -> main) Add learning goals and initial test plan
3f2a91c Add README with project title

This edit, add, commit loop is 80% of daily Git work. Viewing history in detail is covered in git log and diff.


⚑ Shortcut: git commit -am

For files Git already tracks, you can stage and commit in one step:

git commit -am "Update test plan with API tests"

πŸ“ Note: -a does not include new (untracked) files. Use git add for those first.


✍️ Writing Good Commit Messages

A commit message is a note to your future self and your team.

❌ Avoidβœ… Prefer
updateAdd login tests for locked-out users
fixFix flaky checkout test by waiting for the API response
changesRename test data files to match feature names

Rules of thumb: start with a verb in the imperative (“Add”, “Fix”, “Remove”), keep the first line under about 50 characters, and describe what and why, not how. The full conventions are in commit messages and Conventional Commits.


🧭 What Happened Behind the Scenes?

Working directory  ──git add──▢  Staging area  ──git commit──▢  Repository (.git)
   (your files)                (next snapshot)               (saved history)

These three areas are the heart of Git. The next lesson explains them in detail.


πŸ“ Assignment

  1. Create a folder git-practice, run git init and check git status.
  2. Create README.md and notes.txt, stage only README.md, and commit it. Run git status and explain why notes.txt is still untracked.
  3. Stage and commit notes.txt with a good commit message.
  4. Make three more small commits, then run git log --oneline.
  5. Edit a tracked file and commit it with git commit -am.
  6. Bonus: create two changes in one file and use git add -p to commit only one of them.

❓ FAQ

πŸ€” What does git init do?

It creates a hidden .git folder that turns the current folder into a Git repository, so Git can start tracking changes.

πŸ€” What is the difference between git add and git commit?

git add chooses which changes go into the next snapshot (staging). git commit saves the staged changes permanently in the repository history with a message.

πŸ€” What does git add . do?

It stages all new, modified and deleted files in the current folder and its subfolders.

πŸ€” How do I commit with a message in Git?

git commit -m "Your message". Without -m, Git opens your configured editor to write the message.

πŸ€” Why does Git say “Please tell me who you are”?

Your name and email are not configured. Run the commands from Configure Git, then commit again.


🎯 Next Steps

🎬 Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in