Skip to content

Instantly share code, notes, and snippets.

@shreewatsa
Last active August 27, 2024 16:29
Show Gist options
  • Save shreewatsa/9a0d20356d9c58e1704a0687be440e2d to your computer and use it in GitHub Desktop.
Save shreewatsa/9a0d20356d9c58e1704a0687be440e2d to your computer and use it in GitHub Desktop.
Git Cheatsheet

Edit global git config. Remove --global flag to edit project wise git configs:

git config --global --edit;

Git aliases

Global aliases are stored in file ~/.gitconfig
Create Git aliases:

git config --global alias.recent-branches "for-each-ref --sort=-committerdate refs/heads/ refs/remotes/ --format='%(committerdate:iso8601) %(refname:short)'";  # Usage: git recent-branches;
git config --global alias.stashsave '!f() { git stash push -m "$1"; }; f' # Usage: git stashsave "foo";
git config --global alias.aliases "config --get-regexp '^alias\.'"; git aliases;  # Usage: git aliases;

Git commands:

git branch -M main;
git remote add origin [email protected]:<github_username>/<repo_name>.git;
git push -u origin main;

Git diff:

# Export & Import the git diffs.
git diff HEAD > foo.diff;  # Copy this foo.diff to another machine/repo.
git apply foo.diff;

Git stash:

# View stash list and changes interactively using fzf & bat.
export FZF_DEFAULT_OPTS="--bind 'shift-up:preview-half-page-up,shift-down:preview-half-page-down'"
git stash list | fzf --ansi --preview 'git stash show -p $(echo {} | cut -d: -f1) | bat --color=always --language=diff'

# Apply/Pop the stash.
git stash apply/pop stash@{<index_num/stash_message>};  # Stash message is matched fuzzy.
# Best way to ignore files: .gitignore > .git/info/exclude > core.excludefile
git update-index --assume-unchanged
git update-index --no-assume-unchanged
git update-index --skip-worktree
git update-index --assume-unchanged .gitignore

# Ignore files after updating .gitignore file:
git restore —staged .  # If ignored files are in staging.
git rm -r --cached .   # Delete git cache.

Git log

# View the historical changes of a particular file.
git log --follow [--oneline] -- project_root/foo.txt;

# Filtering logs.
git show [email protected] -n 10;  # Show latest 10 commits from author email '[email protected]'
git show --name-only <commit_hash>;  # Show the files changed by <commit_hash>

Git cherrypick

# Copy the commit hash first, then checkout to the branch where you want to paste the changes.
git cherry-pick <commit_hash>;
git cherry-pick --continue;  # In case of conflict, resolve them first. Then, do this.

Git rebase

# To squash first 3 commits,
git log;
git rebase -i <4th_commit_hash>  # Leave 1st commit as it is, fixup on 2nd & 3rd, then :wq
git push --force;

Misc

  1. Use .gitkeep file to track empty directory.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment