Git Workflow Tips and Tricks

Master Git with these essential workflow tips and commands.

Branch Management

Create and manage branches effectively:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Create and switch to new branch
git checkout -b feature/new-feature

# List all branches
git branch -a

# Delete local branch
git branch -d feature/old-feature

# Delete remote branch
git push origin --delete feature/old-feature

# Rename current branch
git branch -m new-branch-name

Commit Best Practices

Write meaningful commit messages:

1
2
3
4
5
6
7
8
9
10
11
12
# Good commit message format
git commit -m "feat: add user authentication

- Implement JWT token generation
- Add login and logout endpoints
- Create user session middleware"

# Amend last commit
git commit --amend

# Interactive staging
git add -p

Stashing Changes

Save work in progress:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Stash current changes
git stash save "WIP: working on feature X"

# List all stashes
git stash list

# Apply most recent stash
git stash apply

# Apply and remove stash
git stash pop

# Apply specific stash
git stash apply stash@{2}

# Clear all stashes
git stash clear

Rebase vs Merge

Keep history clean with rebase:

1
2
3
4
5
6
7
8
9
10
11
12
# Update feature branch with main
git checkout feature/my-feature
git rebase main

# Interactive rebase to clean up commits
git rebase -i HEAD~3

# Continue after resolving conflicts
git rebase --continue

# Abort rebase
git rebase --abort

Useful Aliases

Add these to your .gitconfig:

1
2
3
4
5
6
7
8
9
[alias]
st = status
co = checkout
br = branch
ci = commit
unstage = reset HEAD --
last = log -1 HEAD
visual = log --graph --oneline --all
amend = commit --amend --no-edit

Cherry-picking

Apply specific commits:

1
2
3
4
5
6
7
8
# Cherry-pick a commit
git cherry-pick abc123

# Cherry-pick multiple commits
git cherry-pick abc123 def456

# Cherry-pick without committing
git cherry-pick -n abc123

Undoing Changes

Fix mistakes safely:

1
2
3
4
5
6
7
8
9
10
11
12
# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (discard changes)
git reset --hard HEAD~1

# Revert a commit (create new commit)
git revert abc123

# Discard local changes
git checkout -- filename
git restore filename

Working with Remotes

Manage remote repositories:

1
2
3
4
5
6
7
8
9
10
11
# Add remote
git remote add upstream https://github.com/original/repo.git

# Fetch from remote
git fetch upstream

# Pull with rebase
git pull --rebase origin main

# Push force safely
git push --force-with-lease

These Git techniques will make you more productive and confident!