Linux

git

Distributed version control system for tracking changes in source code.

#development #version-control #git

Initialize Repository

Create a new Git repository.

git init

Clone Repository

Clone a remote repository.

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

Configuration

Set User Name

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

Set Email

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

View Configuration

git config --list

Basic Operations

Check Status

git status

Add Files

Add specific file.

git add [file]

Add all changes.

git add .

Commit Changes

git commit -m "Commit message"

Commit with auto-add of tracked files.

git commit -am "Commit message"

View Commit History

git log

Compact view.

git log --oneline

Branching

List Branches

git branch

Create Branch

git branch [branch]

Switch Branch

git checkout [branch]

Or (Git 2.23+):

git switch [branch]

Create and Switch

git checkout -b [branch]

Or:

git switch -c [branch]

Delete Branch

git branch -d [branch]

Force delete.

git branch -D [branch]

Merging

Merge branch into current branch.

git merge [branch]

Remote Repositories

Add Remote

git remote add [remote] https://github.com/user/repo.git

View Remotes

git remote -v

Fetch Changes

git fetch [remote]

Pull Changes

git pull [remote] [branch]

Push Changes

git push [remote] [branch]

Set upstream and push.

git push -u [remote] [branch]

Undoing Changes

Unstage File

git reset [file]

Discard Local Changes

git checkout -- [file]

Or:

git restore [file]

Amend Last Commit

git commit --amend

Reset to Previous Commit

Soft reset (keep changes staged).

git reset --soft HEAD~1

Mixed reset (keep changes unstaged).

git reset HEAD~1

Hard reset (discard all changes).

git reset --hard HEAD~1

Stashing

Save Changes

git stash

With message.

git stash save "Work in progress"

List Stashes

git stash list

Apply Stash

git stash apply

Apply specific stash.

git stash apply stash@{0}

Pop Stash

Apply and remove stash.

git stash pop

Drop Stash

git stash drop stash@{0}

Tagging

Create Tag

git tag v1.0.0

Annotated tag.

git tag -a v1.0.0 -m "Version 1.0.0"

List Tags

git tag

Push Tags

git push [remote] --tags

Differences

View Changes

Unstaged changes.

git diff

Staged changes.

git diff --staged

Between branches.

git diff [branch1]..[branch2]

Advanced

Rebase

git rebase [branch]

Interactive rebase.

git rebase -i HEAD~3

Cherry Pick

Apply specific commit to current branch.

git cherry-pick <commit-hash>

Clean Untracked Files

Preview.

git clean -n

Remove files.

git clean -f

Remove files and directories.

git clean -fd

Helpful Aliases

Add to ~/.gitconfig:

[alias]
    st = status
    co = checkout
    br = branch
    ci = commit
    unstage = reset HEAD --
    last = log -1 HEAD
    lg = log --oneline --graph --decorate --all