Skip to content

Git and GitHub Commands: A Practical Tutorial with Examples

Git records the history of a project on your own machine. GitHub hosts that history online and adds collaboration tools around it. This guide walks through the command set in the order you are likely to meet it: configuration, staging, commits, history inspection, undo, branching, merging, rebasing, remotes, and finally the fork-and-pull-request loop that most open-source contributions follow. Every command below is shown with the exact syntax you would type, and the surrounding notes explain what changes in your repository when you run it.

Before you start

You need a terminal, a browser, and a Git installation. Windows users can use Command Prompt or PowerShell, or install Git Bash for a Unix-like shell. macOS and Linux ship with a terminal application. Confirm the install by running the version check shown in the code module. A successful install prints a version string such as git version 2.45.2.windows.1. GUI clients exist and are linked from the official Git downloads page, but the walkthrough below stays on the command line.

What Git is and why it helps

Git is a distributed version control system. It records every change you make to a project so you can inspect, restore, or share any earlier state. Four practical benefits come up repeatedly: you can recover a deleted section of code, several developers can work on the same project at once through separate branches, your history survives a local machine failure once it is pushed to a remote, and you can experiment on a branch without risking the main codebase. If an experiment fails, you delete the branch and nothing else changes.

What GitHub adds

GitHub is a web platform that hosts Git repositories in the cloud. Beyond storage, it supplies pull requests, code review, issue tracking, project boards and milestones, Actions for CI/CD, wikis and documentation, and a social layer of follows, stars, and profiles. Other hosts exist: GitLab bundles CI/CD pipelines, Bitbucket integrates with Atlassian tools such as Jira and Trello, and SourceForge supports Git alongside other version control systems. Git and GitHub are not the same thing. Git is the local tool; GitHub is one place to host and collaborate on the result.

Key Git terms in plain language

A repository is the project folder plus its full history. The working directory is the current state of the files on disk. The staging area (also called the index) is a buffer where you assemble exactly what the next commit will contain. A commit is a snapshot with a unique ID and a message; only staged changes go in. A branch is an independent line of development, and a merge combines branches back together. A remote repository lives on a network host. Cloning copies a remote repository locally, pulling fetches and merges remote changes, and pushing uploads local commits. A conflict happens when two branches change the same lines and Git cannot reconcile them automatically. HEAD points at the latest commit on the branch you currently have checked out.

Configure your identity with git config

Your name and email are attached to every commit you make. Set them once with the global flag, then confirm the result. The global flag writes to ~/.gitconfig and applies to every repository on the machine. Dropping the flag writes to the current repository's .git/config instead, which is useful when one project needs a different identity. Run the list command to see the current values.

Create a repository with git init

Run git init from the project root. Git creates a hidden .git directory that holds all metadata and history. Treat that folder carefully: deleting it removes the local history for the project. Once init finishes, the directory is a repository and Git begins tracking changes inside it.

Stage changes with git add

git add moves changes from the working directory into the staging area. Nothing is written to history until you commit. You can stage one file, everything in the current directory, or every change in the project. Files are either tracked (Git already knows them) or untracked (new files Git has not seen). To start tracking a new file, add it. To stop tracking a file while keeping it on disk, run the cached removal command shown in the code module.

Ignore files with .gitignore

A .gitignore file in the project root lists patterns Git should never track. Typical entries cover generated logs, temporary directories, secret configuration files, macOS .DS_Store files, and dependency folders such as node_modules. Each pattern goes on its own line. Git reads the file automatically and skips matching paths.

Read the working state with git status

git status reports three groups: changes staged for the next commit, changes made but not staged, and untracked files. The output tells you what to do next, whether that is staging more work or committing what is already prepared.

Save a snapshot with git commit

A commit takes the staged changes, records a snapshot, assigns a unique hash, and attaches your message. Each commit is a checkpoint you can return to. Write messages in the imperative mood ("Add feature" rather than "Added feature"), keep the subject short, and add a sentence of context when the change is not obvious. The -a flag commits tracked changes without a separate staging step, but it will not pick up brand-new files.

Inspect history with git log

git log lists commits newest first, showing the hash, author, date, and message. Four options cover most needs: --oneline condenses each commit to one line, -n 5 limits the count, a filename restricts output to that file's history, and --graph --oneline draws a simplified branch-and-merge view.

Compare states with git diff

git diff compares two states of the repository. With no arguments it shows unstaged changes. The --staged flag compares the staging area against the last commit. Passing two commit hashes compares those commits. Useful flags include --color for readability, --name-only for a file list, --name-status for file status, and branch1..branch2 for a branch comparison. In large projects, pass a file path to narrow the output, or pipe into grep to filter lines.

Undo work: revert versus reset

These two commands solve different problems, and choosing the wrong one is a common source of lost work. git revert creates a new commit that reverses an earlier commit, so the original history stays intact. git reset moves the branch pointer back to an earlier commit and, depending on the mode, changes the staging area and working directory too. Use revert on shared branches. Use reset on local commits you have not pushed. The three reset modes differ in what they preserve: --soft keeps changes staged, --mixed (the default) unstages them but keeps them in the working directory, and --hard discards everything in both the staging area and the working directory. The --hard mode is the one that can permanently destroy uncommitted work, and any reset rewrites history that collaborators may already have.

Branch and switch with git branch and git checkout

git branch lists branches (the current one is marked with an asterisk), creates a new branch from the current HEAD, and deletes a branch you are not on. The -D flag forces a delete, -m renames, -r lists remote branches, and -a lists both local and remote. git checkout switches to an existing branch, creates and switches with -b, or restores a single file to its state in a given commit. Before switching branches, commit or stash your work so nothing is lost.

Set work aside with git stash

git stash saves uncommitted changes to a stack and resets the working directory to HEAD. That lets you switch context without committing half-finished work. git stash list shows the stack, git stash apply restores the most recent entry (or a specific one with stash@{n}), git stash pop applies and removes it, git stash drop discards one, and git stash clear empties the stack. Because stashes are a stack, keep them short-lived to avoid confusion.

Combine branches with git merge

git merge integrates another branch into the current one. If the current branch has not diverged, Git performs a fast-forward merge and simply moves the pointer. If the branches have diverged, Git performs a three-way merge and creates a merge commit. When the same lines were changed on both sides, Git marks the conflicted regions in the files, and you resolve them by editing, staging with git add, and finishing with git commit.

Replay commits with git rebase

git rebase moves or replays commits from one branch onto another, producing a linear history instead of a merge commit. Use it to bring a feature branch up to date with main before merging, or to tidy commits with interactive rebase. git rebase -i HEAD~n opens an editor listing the last n commits, where you can change pick to edit, squash, or drop. If a conflict appears, resolve it, stage the file, and run git rebase --continue. To abandon the operation and return to the original state, run git rebase --abort.

Choosing between rebase and merge

Merge preserves the real shape of the project: both branches' commits stay, a merge commit records the join, and nothing is rewritten. Rebase produces a clean line but replaces the original commits with new ones that have different hashes. That rewrite is why rebase is risky on a branch others are using. A practical rule: merge shared branches, rebase private ones before you open a pull request. Both commands can produce conflicts, and rebase may ask you to resolve the same conflict more than once while replaying a series of commits.

Copy a single commit with git cherry-pick

git cherry-pick applies the changes from one existing commit onto the current branch and creates a new commit with those changes. It is the tool for pulling a hotfix from one branch into another without merging the whole branch, or for taking one feature out of a larger branch. Conflicts are possible, especially when the picked commit depends on other commits that are not present. Resolve them, stage the file, and run git cherry-pick --continue, or run git cherry-pick --abort to back out.

Set up GitHub and connect a local repository

Register at github.com with an email and a public username, then fill in your profile. To create a repository, use the plus icon in the top menu and choose New repository, give it a name, pick public or private, and confirm. GitHub then shows quick-start commands for connecting an existing local repository. To delete a repository, open it, go to Settings, scroll to the bottom, and use Delete this repository. Deletion is permanent: it removes the remote repository with its commit history, wiki, issues, comments, packages, secret keys, workflow runs, and collaborator associations. To download files without any Git setup, use Code > Download ZIP, or open a single file and click Raw.

Authenticate pushes with Git Credential Manager

Git Credential Manager (GCM) handles the login step when you push or pull from GitHub. On Windows it ships with Git for Windows. On macOS you can install it with Homebrew using the command in the code module. On Linux, follow the GCM documentation. Then point Git at it with the credential.helper configuration shown. On the first push or pull, Git opens a browser window for you to authorize access, and GCM stores the credential so later operations do not prompt again.

Manage remotes with git remote

git remote add registers a URL under a short name so you can push, pull, and fetch against it. git remote -v lists the registered remotes and their URLs. git remote remove unregisters one, and git remote rename changes its name. The conventional name for the primary remote is origin.

Copy a repository with git clone

git clone downloads a remote repository, creates a directory named after it, initializes a local repository, pulls the full commit history, and registers the source as origin. Pass a directory name to clone into a different folder, -b to check out a specific branch, or --depth to limit how much history is downloaded.

Fetch versus pull

git fetch downloads new commits and updates remote-tracking branches such as origin/main, but leaves your working directory and current branch untouched. You can then review the changes and merge or rebase them yourself. git pull does the fetch and the merge in one step, which is faster but can drop a conflict on you immediately. Use fetch when you want to inspect first; use pull when you want the update applied now. The --rebase flag makes pull rebase instead of merge, and --all and --prune on fetch cover multiple remotes and stale branch references.

Upload commits with git push

git push sends local commits to a remote branch and updates that branch to match yours. The -u flag sets the remote branch as the default upstream so later pushes need only git push. The --force flag overwrites the remote branch and can destroy other people's work, so use it only when you are certain. If the remote has commits you do not have, the push is rejected; pull, resolve any conflicts, commit, and push again.

Mark releases with git tag

Tags label specific commits, typically releases. A lightweight tag is just a pointer. An annotated tag stores the tagger's name, email, date, and a message as a full object. Create one with git tag <tagname> or git tag -a <tagname> -m "message", list with git tag, inspect with git show, and delete with git tag -d. Tags are not pushed automatically: push one with git push origin <tagname> or all of them with git push origin --tags. Checking out a tag puts you in a detached HEAD state, which means you are not on any branch.

Contribute through forks and pull requests

A fork is your own copy of someone else's repository under your account, which lets you change a project without touching the original. On GitHub, open the repository, click Fork, and choose a target if you belong to multiple organizations. Clone your fork locally, add the original repository as a remote named upstream, fetch from it, and merge upstream/main to stay current. When your changes are ready, push them to your fork, open the original repository (not your fork), go to Pull requests, click New pull request, and select your branch. The left side of the comparison is the base repository receiving the change; the right side is your fork. Add a descriptive title and description, and the maintainers will review, request changes, or merge.

A decision checklist for undo and integration

Use this checklist before you run an undo or integration command. First, ask whether the commit has been pushed to a branch others use. If yes, prefer git revert over git reset. Second, ask whether you need the original commits preserved. If yes, use git merge; if a linear history matters more and the branch is private, use git rebase. Third, ask whether you want one commit or the whole branch. One commit means git cherry-pick; the whole branch means merge or rebase. Fourth, if you are not ready to commit at all, use git stash rather than reset. Fifth, if a conflict appears, resolve the file, stage it with git add, and then continue the operation that paused: git commit for a merge or pull, git rebase --continue for a rebase, git cherry-pick --continue for a cherry-pick.

Worked example: one conflict, three commands

Suppose your log shows a commit with hash 1a2b3c4d5e6f7g8h9i0jklmnopqrstuvwx that added a feature, and you want that change on another branch. To copy just that commit, switch to the target branch and run git cherry-pick 1a2b3c4d5e6f7g8h9i0jklmnopqrstuvwx. If the same lines were changed on both sides, Git pauses and marks the file. Edit the file, run git add on it, then git cherry-pick --continue. To instead undo that commit on the branch where it already lives, run git revert 1a2b3c4d5e6f7g8h9i0jklmnopqrstuvwx, which creates a new commit that reverses it and leaves the original in place. To move the branch pointer back before that commit on a local-only branch, run git reset --soft 1a2b3c4d5e6f7g8h9i0jklmnopqrstuvwx, which keeps the changes staged. The same hash drives three different outcomes; the choice depends on whether you want the change copied, reversed, or uncommitted.

Field map: where each command moves data

Git has three places a change can live: the working directory, the staging area, and the commit history that HEAD points into. git add moves changes from the working directory into the staging area. git commit moves the staging area into history. git diff with no arguments compares working directory against staging; git diff --staged compares staging against the last commit. git checkout <commit> -- <file> pulls a file from history back into the working directory. git reset --soft moves the branch pointer but leaves staging and working directory alone; --mixed also resets staging; --hard resets all three. git stash copies working directory and staging into a stash entry and resets the working directory to HEAD. Reading the map this way makes the reset modes and the diff variants easier to remember.

Frequently asked questions

What is Git?

Git is a distributed version control system created by Linus Torvalds in 2005. It tracks changes to code, supports collaboration, and keeps a full history of the project on each machine that has a copy.

Where does the name Git come from?

The word is British slang for an unpleasant person. Torvalds chose it humorously, describing himself that way.

Which commands do I need first?

git init creates a repository, git add stages changes, git commit saves them, git push uploads to a remote, and git pull fetches and merges remote changes. Those five cover the basic loop.

What is Git Bash?

Git Bash is a Windows command-line environment that emulates a Unix shell. It bundles the Git command-line tools, a Bash shell, and path translation between Unix-style and Windows paths. It is installed as part of the Git for Windows package.

How do I remove Git from a project folder?

Delete the hidden .git directory. On the command line, run rm -rf .git. That removes all version history for the project, so use it only when you intend to uninitialize the repository. In a file manager, enable hidden folders first.

What are Git hooks?

Scripts that run automatically on specific Git events, such as committing or merging. They enforce policies, automate tasks, and connect Git to other tools.

What are Git submodules?

A way to nest one Git repository inside another as a subdirectory. They let you keep separate repositories for different components while managing them from a single parent. To clone a repository with its submodules, add --recursive to git clone.

What is a fast-forward merge?

When the branch being merged has not diverged from the target, Git simply moves the branch pointer forward to the latest commit and creates no merge commit. The history stays linear. If the branches have diverged, a three-way merge creates a merge commit instead.

What is Git LFS?

Large File Storage is an extension that keeps large and binary files outside the repository while storing pointers to them inside it.

What is GitHub used for?

Hosting Git repositories online, with collaboration and project management features on top: pull requests, issue tracking, and Actions for CI/CD.

Who owns GitHub?

Microsoft, which acquired GitHub in 2018.

What are GitHub Actions?

A CI/CD service built into GitHub that automates building, testing, and deploying code from the repository.

What is GitHub Pages?

A free service that publishes static websites directly from a repository. Push to the designated branch and GitHub serves the site at a URL like yourusername.github.io/your-repo-name. A custom domain can be attached later.

What does IPTV GitHub mean?

Repositories on GitHub that host lists of IPTV channels, which IPTV applications can use to stream television over the internet.

When should I use git revert instead of git reset?

Use revert on any commit that has already been pushed to a shared branch, because it adds a new commit and leaves history intact. Use reset only on local commits you have not shared, and avoid --hard unless you are certain you want to discard uncommitted work.

What is the difference between git fetch and git pull?

Fetch downloads remote changes and updates remote-tracking branches without touching your working directory. Pull fetches and merges in one step, so it changes your current branch immediately. Fetch first when you want to review the incoming changes.