AI Development

Essential Git Commands for Beginners (and Their Alternatives)

Git commands on a laptop beneath the title Essential Git Commands for Beginners

Git keeps a history of your files as you work, so you can make changes without losing the versions that worked before. Whether you're working on a single file or a large project, you can save working versions and return to them if something goes wrong. No more keeping copies named app-2.js and app-3.js just in case.

Git works locally on your computer. Services like GitHub and GitLab let you store your repository online, giving you an additional layer of backup if your computer breaks or gets lost. They also make it easy to synchronize your work between computers and collaborate with other developers.

Just remember that only the commits you've pushed are stored online.

Here are the essential Git commands, what they do, and the common alternatives you'll encounter.

1. Getting started with Git

Check your Git installation

git --version

Displays your installed Git version. If Git isn't installed, download it from git-scm.com.

Configure your name

git config --global user.name "Your Name"

Sets the author name attached to your commits. It can be your real name or a developer alias. It doesn't have to match your GitHub username.

The --global option applies the setting to your user account on this computer.

Configure your email

git config --global user.email "you@example.com"

Sets the email address attached to your commits. It isn't necessarily your Windows, Outlook, or computer login email.

For GitHub to associate your commits with your account, use an email verified on GitHub or your GitHub-provided private email address.

To check these settings, use git config user.name and git config user.email.

Important: These settings don't create a Git account. Git works locally, and you configure each computer separately.

Create a new Git repository

git init -b main

Initializes Git in your current folder, turning it into a Git repository.

The -b means initial branch. You can call it main, production, or anything else. main is a common convention, while master was the historical default.

Alternative: git init creates the repository using your configured default branch name.

Clone an existing repository

git clone https://github.com/user/project.git

Downloads an existing Git repository to your computer, including its files and commit history.

This works with GitHub, GitLab, Bitbucket, and other accessible Git repositories.

Use git init when starting a local repository. Use git clone when downloading one that already exists.

2. Checking your work

Before saving changes, it helps to understand three terms:

Untracked: A new file Git hasn't started tracking.

Unstaged: Changes you haven't selected for your next commit.

Staged: Changes you've selected for your next commit using git add.

Staging doesn't save a commit. It prepares changes for one.

Check the project's status

git status

Shows your current branch, modified files, staged changes, and untracked files.

It's a quick way to see what's happening in your repository before committing or switching branches.

See what changed

git diff

Shows changes to tracked files that haven't been staged.

Git normally compares text line by line. Lines starting with - were removed, while lines starting with + were added.

For example:

- console.log("Hello");
+ console.log("Hello, world!");

Alternative: git diff --staged displays changes already staged for your next commit. You'll also encounter git diff --cached, which means the same thing.

3. Adding and committing changes

A commit saves a snapshot of your staged changes to your local Git history.

Stage one file

git add index.html

Stages changes to the specified file for your next commit.

Stage changes in the current directory

git add .

Stages new, modified, and deleted files inside your current directory and its subdirectories.

A directory simply means a folder. A subdirectory is a folder inside another folder.

Stage changes across the entire repository

git add -A

Stages all new, modified, and deleted files across the repository, even if your terminal is currently inside a subdirectory.

Alternative: git add --all does the same thing.

If you're in the project's main folder, git add . and git add -A normally have the same result. Inside a subfolder, git add -A reaches the entire repository.

Tip: Use git status to check what you're staging. You may not want every changed file included in the same commit.

Save a commit

git commit -m "Add homepage"

Creates a new local commit containing your staged changes.

The -m supplies the commit message. It can be a short description or a longer sentence.

Alternative: Running git commit without -m opens your configured editor, where you can write a longer message.

View your commit history

git log --oneline

Shows your previous commits in a compact list, with an abbreviated commit ID and message on each line.

Alternative: git log shows more detailed history.

You may also see HEAD beside a commit. This represents your current position in Git, normally through the branch you're working on.

4. Working with GitHub and other remote repositories

Your Git project exists locally until you upload its commits somewhere else.

A remote repository is another Git repository, usually hosted online on GitHub or GitLab.

If your computer breaks, commits you've pushed to GitHub can be downloaded again. Local changes and commits you haven't pushed aren't automatically backed up there.

Before connecting a new local project to GitHub: Create an empty GitHub repository without automatically adding a README or other starter files. Otherwise, GitHub creates its own initial commit, which can complicate the first push from your existing local project.

Connect to an online repository

git remote add origin https://github.com/user/project.git

Connects your local repository to the specified remote repository.

origin is simply the conventional nickname for that remote. You could name it cloud, online, or github instead.

For example:

git remote add cloud https://github.com/user/project.git

Repository URLs don't universally require the .git suffix. The easiest approach is to copy the clone URL from your hosting provider.

See connected remote repositories

git remote -v

Lists your configured remotes and their URLs.

The -v stands for verbose, meaning more detailed output.

You'll normally see a fetch URL for downloading changes and a push URL for uploading them. They're usually identical, but they can differ.

A project can also have multiple remotes, such as one on GitHub and another on GitLab.

Push a branch for the first time

git push -u origin main

Uploads your local main branch and establishes its upstream tracking relationship.

The -u means set upstream. It tells Git which remote branch this local branch should track.

Alternative: git push --set-upstream origin main does the same thing.

If you've named your remote cloud, replace origin with cloud.

You don't always need -u: cloned branches often already have tracking configured, and some Git configurations automatically establish upstream tracking on the first push.

Push your commits

git push

Uploads your local commits to the configured remote branch.

Once your upstream is established, you can normally use this shorter command.

Remember that git commit saves locally, while git push uploads your commits.

Download and integrate changes

git pull

Retrieves changes from a remote repository and integrates them into your current branch.

Without arguments, Git normally uses the upstream configured for your current branch.

This is essential when working across multiple computers. For example, after pushing work from your desktop, you can pull those commits onto your laptop.

It's also useful after merging branches through the GitHub or GitLab website. Switch to the affected local branch, such as main, and pull to update it.

Alternative: git pull --ff-only only updates your branch when Git can move it forward without reconciling divergent histories. Otherwise, it stops.

Alternative: git pull --rebase retrieves remote changes and replays your local commits on top. This can keep the history more linear, but rewrites the replayed commit identities and may require conflict resolution.

Tip: Check which branch you're on before pulling. Git doesn't automatically choose main just because it's your primary branch. Pulling with uncommitted changes can also cause problems, so it's usually best to start with a clean working tree.

Fetch changes without integrating them

git fetch

Downloads new information and commits from your configured remote without merging or rebasing them into your current branch.

Alternative: git fetch origin explicitly chooses the remote named origin.

If nothing appears in your terminal, that usually means there was nothing new to report. Fetch doesn't examine or report changes you've just made locally.

Difference: git fetch retrieves remote updates. git pull retrieves them and attempts to integrate the selected branch into your current branch.

5. Working with branches

Branches let you develop features or experiment separately from another version of your project.

List your branches

git branch

Displays local branches. An asterisk marks your current branch.

Create and switch to a new branch

git switch -c feature1

Creates a new branch named feature1 and switches to it.

The -c stands for create.

Older alternative: git checkout -b feature1

The older checkout command handles several different operations. git switch is more specific and generally easier to understand.

Switch to an existing branch

git switch main

Switches to the existing main branch. You can replace main with any other existing branch name.

Older alternative: git checkout main

Without -c, git switch normally switches to an existing branch rather than creating a new one.

Merge another branch

git merge feature1

Integrates changes from the feature1 branch into your current branch.

For example, switch to main first if you want to merge feature1 into main.

Git combines compatible changes automatically, including modified and deleted code. If both branches changed something incompatibly, Git may require you to resolve a conflict.

A merge doesn't simply keep every old function or blindly copy both versions of your project together.

Delete a branch

git branch -d feature1

Deletes the specified local branch after its changes have been appropriately merged.

The -d stands for delete. Git normally protects you from deleting a branch with unmerged changes using this option.

6. Undoing changes and mistakes

Git can restore earlier versions of files and reverse commits. However, some commands discard uncommitted work, so check what they'll affect before running them.

Discard unstaged file changes

git restore index.html

Restores the file's working contents from the staging area, discarding its unstaged modifications.

If the file has no staged changes, this normally restores its last committed version.

Older alternative: git checkout -- index.html

Warning: Discarded uncommitted changes may not be recoverable through Git.

Unstage a file without deleting your changes

git restore --staged index.html

Removes the file's staged changes from your next commit while preserving your working edits.

Older alternative: git reset HEAD index.html

This is useful when you've accidentally staged a file you didn't intend to commit.

Reverse a commit

git revert HEAD

Creates a new commit that reverses the changes introduced by your latest commit.

Unlike rewriting history, this preserves the original commit and records the reversal. That's especially useful when working with commits already shared with other developers.

Temporarily set aside unfinished work

git stash

Temporarily saves staged and unstaged changes to tracked files and clears them from your working tree.

Useful when you're halfway through a feature but need to switch tasks before committing.

Use git stash pop to reapply the most recent stash and remove its stash entry if the application succeeds.

Alternative: git stash -u includes untracked files too.

A stash is temporary storage inside your local Git repository, not an online backup.

7. Files Git should ignore

Most programming projects should include a .gitignore file.

It tells Git which untracked files and folders to ignore, keeping unnecessary generated files and sensitive information out of your commits.

Here's a simple example for a JavaScript project:

# Installed packages
node_modules/

# Environment files
.env
.env.*
!.env.example

# Generated output
dist/
build/
coverage/

# Logs
*.log

# Operating system files
.DS_Store
Thumbs.db

node_modules/ contains installed JavaScript dependencies. These can normally be reinstalled using the project's package files, so there's no need to commit thousands of dependency files.

.env files commonly contain environment variables, including API keys, passwords, connection strings, and project-specific configuration. Keep secrets out of public repositories.

dist/ and build/ often contain generated output that can be recreated, although the correct ignore rules depend on your framework.

Files such as package.json and package-lock.json should generally be committed because they describe your project's dependencies.

Important: Adding a file to .gitignore doesn't automatically stop tracking it if you've already committed it. And ignoring a previously exposed secret doesn't remove it from Git history.

The everyday Git workflow

For most routine development, you'll use only a handful of these commands.

If you're returning to a project that may have newer remote commits, start on the correct branch and update it before editing.

git status
git pull --ff-only

Then make your changes.

When you're ready to save them:

git status
git diff
git add -A
git commit -m "Describe your changes"
git push

This example assumes the branch already has upstream tracking, your working tree is clean before pulling, and you intend to stage all project changes.

That's the everyday workflow. Use branches when developing separate features, git restore when you need to discard edits, and git revert when you need to reverse committed work.

You don't need to memorize every Git command. Learn the basic workflow, understand what your commands are changing, and use the others when the situation calls for them.