Fundamentals 37 min read

Master Git: Essential Commands, Workflows, and Best Practices

This comprehensive guide explains Git's core concepts, configuration, common commands, branching strategies, hooks, submodules, and troubleshooting tips, providing clear examples and code snippets to help developers efficiently manage version control in any project.

ITPUB
ITPUB
ITPUB
Master Git: Essential Commands, Workflows, and Best Practices

Git Core Concepts

Git organizes files into four areas: Workspace (working directory), Index/Stage (staging area), Repository (local .git folder), and Remote (server‑side repository).

Git flow diagram
Git flow diagram

Configuring Git

# Global user configuration
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"

# Alias shortcuts
$ git config --global alias.co checkout
$ git config --global alias.ss status
$ git config --global alias.cm commit
$ git config --global alias.br branch
$ git config --global alias.rg reflog
$ git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

# Remove a global setting
$ git config --global --unset alias.xxx
$ git config --global --unset user.xxx

Viewing Git Information

# List all configuration
$ git config --list
# Show user config file
$ cat ~/.gitconfig
# Show repository config
$ cat .git/config
# List files in the index
$ git ls-files
# Show reflog (history of HEAD moves)
$ git reflog
# Show all git commands
$ git --help -a
# Show HEAD reference
$ cat .git/HEAD

# Log examples
$ git log --oneline --graph --all --author "username" --before="2020-01-01" --after="2019-01-01"

Reflog Details

Shows a list of times the HEAD pointer changed (e.g., checkout, commit, reset). It does not record uncommitted changes.

Git periodically prunes reflog entries, so very old entries may disappear.

Log Graph Symbols

*   commit
|   branch forward
/   branch split
\   merge
|/  new branch

Common Git Commands

add : Move files from workspace to staging area.

# Add specific files
$ git add file1 file2
# Add a directory (recursively)
$ git add dir/
# Add everything in the current directory
$ git add .
# Remove files from staging
$ git rm file1
# Stop tracking a file but keep it locally
$ git rm --cached file
# Rename a file
$ git mv old new

status : Show workspace and staging status.

$ git status

commit : Record staged changes.

# Simple commit
$ git commit -m "Message"
# Add and commit in one step (tracked files only)
$ git commit -am "Message"
# Amend the previous commit (keep or edit message)
$ git commit --amend
$ git commit --amend -m "New message"
# Skip hooks
$ git commit --no-verify

push & pull : Synchronize with remote.

# Push local branch to remote
$ git push -u origin branchName
# Push all branches
$ git push --all origin
# Pull and merge
$ git pull origin branchName
# Force push (use with caution)
$ git push --force origin

branch : Manage branches.

# List branches
$ git branch          # local
$ git branch -r       # remote
$ git branch -a       # all
# Create a new branch
$ git branch newFeature
# Switch to a branch
$ git checkout newFeature
# Create and switch in one step
$ git checkout -b newFeature
# Delete a branch
$ git branch -d oldFeature
$ git branch -D oldFeature   # force
# Delete remote branch
$ git push origin --delete remoteBranch

merge : Combine branches.

# Fast‑forward merge (default)
$ git merge
# No fast‑forward (creates a merge commit)
$ git merge --no-ff
# Squash merge (single commit, no merge commit)
$ git merge --squash

rebase : Reapply commits on top of another base (links provided for further reading).

stash : Temporarily save uncommitted changes.

# Save all changes
$ git stash
# Save with a message
$ git stash save "work in progress"
# Include untracked files
$ git stash -u
# List stashes
$ git stash list
# Apply a stash without dropping it
$ git stash apply stash@{0}
# Apply and drop
$ git stash pop stash@{0}
# Drop a stash
$ git stash drop stash@{0}
# Clear all stashes
$ git stash clear

diff : Compare changes.

# Workspace vs. index
$ git diff
# Index vs. last commit
$ git diff --cached
# Specific file
$ git diff filename
# Between branches
$ git diff branchA..branchB
# Between commits
$ git diff commit1..commit2

remote : Manage remote repositories.

# List remotes
$ git remote -v
# Add a remote
$ git remote add origin https://github.com/user/repo.git
# Change URL
$ git remote set-url origin [email protected]:user/repo.git
# Remove a remote
$ git remote rm origin

tag : Mark specific points (usually releases).

# Create lightweight tag
$ git tag v1.0
# Annotated tag with message
$ git tag -a v1.0 -m "Release 1.0"
# Push a tag
$ git push origin v1.0
# Push all tags
$ git push origin --tags
# Delete a tag locally and remotely
$ git tag -d v1.0
$ git push origin :refs/tags/v1.0

Creating a Git Project

Initialize locally and add remote

$ git init
$ git remote add origin https://github.com/yourname/yourrepo.git

Clone an existing remote repository

$ git clone https://github.com/yourname/yourrepo.git
# Or clone into a specific directory
$ git clone https://github.com/yourname/yourrepo.git project-name

Branch Management Guidelines

Typical workflow for larger projects uses multiple long‑living branches:

develop : Daily development branch.

test : Feature‑complete code that passes local tests.

release : Pre‑release branch for final verification.

master : Production‑ready code.

Developers pull and commit to develop, merge to test after self‑testing, promote to release for staging, and finally merge to master and tag a version. Bug fixes are done on a temporary bug branch based on the latest stable branch.

Git Hooks

Hooks are scripts stored in .git/hooks that run at various points (client‑side or server‑side). Common client‑side hooks include pre‑commit, which can run linters or tests before a commit.

# Install pre‑commit via npm
npm install pre-commit --save-dev

# Example package.json snippet
"scripts": {
  "build": "tsc",
  "eslint": "eslint src --ext .ts",
  "eslint:fix": "eslint src --ext .ts --fix"
},
"pre-commit": ["eslint"]

Skip the hook with git commit --no-verify if needed.

Common Issues & Solutions

Unrelated histories : Use git pull origin branch --allow-unrelated-histories or git merge --allow-unrelated-histories when merging two independent histories.

Merge conflicts : Resolve files, then git add and commit, or abort with git merge --abort.

HEAD detached state : After git checkout <commit>, HEAD points to a commit, not a branch. Create a new branch to keep work: git checkout -b newBranch.

Reset vs. Revert : git reset rewrites local history (use only for unpublished commits). git revert adds a new commit that undoes changes, safe for public history.

Missing remote branches : Run git fetch --all to update local references.

Authentication failures : Verify remote URL protocol (SSH vs HTTPS) and update credentials or SSH keys.

Locked index : Delete .git/index.lock if a previous Git process crashed.

Empty folder tracking : Add a placeholder file such as .gitkeep because Git does not track empty directories.

Submodules : Use git submodule add URL path, then git submodule update --init --recursive to clone with submodules.

References

Git Book, Pro Git (Chinese edition), git‑recipes, "How to Use Git Elegantly", "Using Git Submodules in Large Projects", GitHub API v3 documentation, and various community articles.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

hookscommand-linesubmodule
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.