Fundamentals 37 min read

Master Git: Essential Commands, Workflows, and Best Practices

This comprehensive guide covers Git fundamentals, including workspace concepts, configuration, common commands, branch management, merging strategies, hooks, and troubleshooting tips, providing developers with a complete reference to efficiently use Git for version control in any project.

Open Source Linux
Open Source Linux
Open Source Linux
Master Git: Essential Commands, Workflows, and Best Practices

Git Flow Diagram

Workspace

: 工作区 Index / Stage: 暂存区 Repository: 仓库区(或本地仓库) Remote: 远程仓库

Configuring Git

# Configure global user
$ git config --global user.name "用户名"
$ git config --global user.email "git账号"
# 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 alias
$ git config --global --unset alias.xxx
$ git config --global --unset user.xxx

Viewing Git Information

# List system config
$ git config --list
# Show user config
$ cat ~/.gitconfig
# Show repository config
$ cat .git/config
# List files in the index
$ git ls-files
# Show reflog
$ git reflog
# Show help for all commands
$ git --help -a
# Show HEAD reference
$ cat .git/HEAD
# Show commit log (examples)
$ git log --oneline --grep="关键字" --graph --all --author "username" --reverse -n --stat --abbrev-commit --pretty=format:"xxx"

git reflog

Shows a list of HEAD changes over time. It records commits when you switch branches, commit, or reset, but not when you checkout a file or stash changes, because those actions do not create new commits.

Git periodically cleans up unused reflog entries, so old entries may disappear.

git log graph

In Git, a branch is a pointer. Creating a new branch creates a new pointer based on the current one. Switching branches moves HEAD to point to a different branch or commit.

Symbols:

*	表示一个 commit
|	表示分支前进
/	表示分叉
\	表示合入
|/	表示新分支

Common Git Commands

# Show status of workspace and index
$ git status
# Add all changes to index
$ git add .
# Commit with message
$ git commit -m "本次提交说明"
# Shortcut: add and commit (tracked files only)
$ git commit -am "本次提交说明"
# Push local branch to remote
$ git push -u origin branchName
# Pull remote branch
$ git pull origin branchName
# Merge a branch
$ git merge branchName
# List local branches
$ git branch
# List all branches (local + remote)
$ git branch -a
# Switch branch
$ git checkout branchName
# Stash changes
$ git stash
# Apply stash
$ git stash pop

Detailed Command Explanations

add

Add files to the index (staging area). git add .: stages all changes in the current directory. git add -u: stages modifications and deletions of tracked files. git add -A: stages all changes, including new, modified, and deleted files.

status

# Show status of workspace and index
$ git status

commit

# Commit staged changes with a message
$ git commit -m "本次提交的说明"
# Add and commit in one step (tracked files only)
$ git commit -am "本次提交的说明"
# Amend the previous commit
$ git commit --amend
# Amend with a new message without opening editor
$ git commit --amend --no-edit

Never amend a commit that has already been pushed to a public repository.

push & pull

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

branch

# List branches
$ git branch -a
# Create a new branch
$ git branch newBranch
# Switch to a branch
$ git checkout newBranch
# Create and switch in one step
$ git checkout -b newBranch
# Delete a branch
$ git branch -d oldBranch
# Force delete a branch
$ git branch -D oldBranch
# Rename current branch
$ git branch -m newName

merge

# Fast-forward merge (default)
$ git merge
# No fast-forward (creates a merge commit)
$ git merge --no-ff
# Squash merge (does not create a merge commit)
$ git merge --squash

rebase

Rebase rewrites commit history by moving a series of commits onto a new base. It is useful for linearizing history but should not be used on public branches.

stash

# Save uncommitted changes
$ git stash
# Save with a message
$ git stash save "message"
# 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 workspace with index
$ git diff
# Compare index with last commit
$ git diff --cached
# Compare two branches
$ git diff branchA..branchB
# Compare two commits
$ git diff commit1..commit2

remote

# List remotes
$ git remote
# Show remote URLs
$ git remote -v
# Add a remote
$ git remote add origin <url>
# Change remote URL
$ git remote set-url origin <newurl>
# Remove a remote
$ git remote rm origin

tag

# Create a lightweight tag
$ git tag v1.0
# Create an annotated tag
$ git tag -a v0.1 -m "version 0.1 released"
# List tags
$ git tag
# Show tag details
$ git show v1.0
# Push a tag
$ git push origin v1.0
# Push all tags
$ git push origin --tags
# Delete a local tag
$ git tag -d v0.1
# Delete a remote tag
$ git push origin :refs/tags/v0.1

Deleting Files

# Delete from index and workspace
$ git rm filename
# Delete only from index (keep in workspace)
$ git rm --cached filename

Reset, Revert, and Cherry-pick

# Reset (soft, mixed, hard)
$ git reset --soft HEAD~1   # keep changes in index
$ git reset --mixed HEAD~1  # keep changes in workspace
$ git reset --hard HEAD~1   # discard all changes
# Revert a commit (creates a new commit that undoes changes)
$ git revert <commit_id>
# Cherry-pick a commit onto current branch
$ git cherry-pick <commit_id>

Creating a Git Project

# Initialize a new repository and add remote
$ git init
$ git remote add origin <repo_url>
# Or clone an existing remote repository
$ git clone <repo_url>
$ git clone <repo_url> <project-name>

Branch Management Guidelines

Typical workflow uses multiple long‑living branches:

develop : development branch where daily changes are merged.

test : testing branch after feature integration.

release : pre‑release branch for final verification.

master : production branch; code is deployed from here.

bug : short‑lived branch created from release or master to fix urgent issues.

Git Hooks

Hooks are scripts stored in .git/hooks that run at various points in the Git workflow. They can be client‑side (e.g., pre‑commit) or server‑side.

pre‑commit

Runs before a commit is created. It can run linters, tests, or other checks. If the script exits with a non‑zero status, the commit is aborted.

# Install pre‑commit via npm
npm install pre-commit --save-dev
# Configure in package.json
"pre-commit": ["eslint"]
# Skip pre‑commit checks
$ git commit --no-verify

Common Issues and Solutions

“fatal: refusing to merge unrelated histories” – use --allow-unrelated-histories with git pull or git merge.

Merge conflicts – resolve files, then git add and git commit or abort with git merge --abort.

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

Locked repository – delete .git/index.lock if a previous Git process crashed.

Push rejected because of non‑fast‑forward – pull and merge first, or force push if appropriate.

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.

workflowGitcommand-lineVersion ControlBranch Management
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

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.