Git Snippets
Source: Git - Documentation
# Stage (add) a file for commit and commit changegit add path/to/file/in/repositorygit commit -m"my message"
# Clone (download) a repositorygit clone url# Clone only a branchgit clone url --branch branch_name --single-branch
# Clone, but only populate files present in the root directorygit clone --sparse url
# Only fetch the latest commitgit clone --depth=1 url
# Check differences in file from current edits and maingit diff note/my-note.md
# Check differences in a commit and commit minus N## Last commit differencegit diff HEAD~1git diff HEAD~3git diff commithash~1## Differences of a file compared to HEADgit diff notes/note.md
# Show git commit history of specified filegit log -p -- <filename>## -p : --patch means it will produce patch text, like commit, file and diff information
# Show git log history including change diffsgit log -p
# Browse repository and logtig
# Show, viewing an old version of a filegit show <commit-hash>:<path-to-file># View old version of a file examplegit show 3a6e7b9:src/main.js
# Find string pattern in repository filesgit grep string# or# -n : show line numbergit grep -n "string pattern"
# Edit commits, interactive rebasegit rebase -i HEAD~5# rebase -i : interactive rebase using editor# HEAD~5 : include last 5 commits from HEAD# Can be used to reorder, pick, reword, edit, squash, fix, drop, and other actions
# Abort a rebase in progressgit rebase --abort
# Windows git bash## Graphical User Interfacesgit guigitk
# Add all directories as safe directories## bash, nugit config --global --add safe.directory '*'## PowerShellgit config --global --add safe.directory *
# Set private key to sign withgit config --global user.signingkey 0A46826A!
# Signing a commit with -Sgit commit -a -S -m 'Signed commit'
# See and verify a signature on a commitgit log --show-signature -1
# Tagginggit tag -a v1.0 -m "pre digital garden"
# Checkout only a subset of files, useful for selecting which files you wantgit sparse-checkout set MY/DIR1 SUB/DIR2# Change to a sparse checkout with all files (at any depth) under MY/DIR1/ and SUB/DIR2/# For files in the the working copy (plus all files immediately under MY/ and SUB/ and the toplevel directory)
# List directories or pattersn in sparse-checkout filegit sparse-checkout list
# Repopulate all files in repository, remove sparse-checkout patternsgit sparse-checkout disable
# Submodules - add a submodule into a specific directory in current repositorygit submodule add https://github.com/chaconinc/DbConnector dbconnfolder
# Submodules - initialize existing module inside a repository and fetch all data from the projectgit submodule initgit submodule update
# Make changes to submodule and parent repositorycd submodulegit commit -m"add file"git submodule updatecd ..git add path/to/your/submodulegit commit -m "Updated submodule to latest main branch"
# Submodules - clone, initialize all submodules and update each submodule in the repositorygit clone --recurse-submodules https://github.com/chaconinc/MainProject
# Get only one commit or range of commits for a branchgit cherry-pick <commit-hash>## Get range or commitsgit cherry-pick <start-hash>^..<end-hash>
# Stash changes temporarily and retrieve them (pop) after a pull from remotegit stashgit pullgit pop
# Stash the changes in a dirty working directory away with git stash# Temporarily saves your local changes away and reverts the working directory to match the HEAD commit, save changes using stashgit stash --include-untrackedgit stash push -u -m "work in progress on feature Y"## push - creates a new stash entry for popping later to describe changes## -u or --include-untracked - includes all change and untracked files## -m or --message - provide a message describing changes## Complete work in other branch, then pop changes againgit stash pop
# See stashed changesgit stash list
# Use binary search to find the commit that introduced a bug with git bisect## Use the hash of the commit that is known to have the bug and a hash of a commit with a good commit## that does not have a bug. For example, HEAD has a the bug and goodcommithash has the working codegit bisect startgit bisect bad HEADgit bisect good goodcommithash## Have git guide on the commit with the issue
# Manage reference logs (reflog) information with git reflog, useful for referencing tips of branches, undoing changes# Show log to find a previous commit or deleted commit, branchesgit reflog showgit log -g --abbrev-commit --pretty=oneline# See refog of branchgit reflog show test_branch# Return to a previous hash in case to "travel back in time" in a separate branchgit checkout -b recovery-branch <hash># Return to commit one previous to HEAD in a separate branchgit checkout -b example-branch HEAD@{1}
# Git Maintenance tasks to optimize performance and efficiency of repositories like garbage collection, repacking## Manually start maintenancegit maintenance run
## Register current repository for daily maintenancegit maintenance register### Unregister repository for maintenancegit maintenance unregister
## Start maintenance for a repositorygit maintenance start## Stop maintenancegit maintenance stop
# Set up signing keysgpg --list-secret-keys --keyid-format=longgit config --global user.signingkey <your-key-id>git config --global commit.gpgsign true
# Change git commits information## Start interactive rebase (-i) with optional commit hash for range to target## Choose commits to editgit rebase -i hash002## Make changesgit commit --amend <amend information>## Example: change commit authorgit commit --amend --author="John Smith <John.Smith@email.com>"## Continue rebase until all selected commits are changed## Identify conflicts during rebasegit status## Make changes and continuegit rebase --contiue
# Undo a commit to make changes to commit# from https://stackoverflow.com/questions/927358/how-do-i-undo-the-most-recent-local-commits-in-gitgit commit -m "Something terribly misguided" # (0: Your Accident)git reset HEAD~ # (1)# === If you just want to undo the commit, stop here! ===# [ edit files as necessary ] # (2)git add . # (3)git commit -c ORIG_HEAD # (4)
# Cleanup unnecessary files and optimize the local repositorygit gc# Usually done automatically with other git porcelain commands like git status, commitCreate a new repository - git init, add
Section titled “Create a new repository - git init, add”#1: Create a folder for this project on your local hard drivemkdir my-project
#2: change into this foldercd my-project
#3: initialize a new, empty Git repository heregit init
# after having written some code + created some files#4: add all changes to the next (= first) commitgit add .
#5: create this first commitgit commit -m "Initial commit"
# git command and add filesgit commit -am"message"
# Add all todo.txt filesgit add *todo*.txtCreate a local repository for backup and synchronization
Section titled “Create a local repository for backup and synchronization”Source: https://stackoverflow.com/questions/10603671/how-to-add-a-local-repo-and-treat-it-as-a-remote-repo
git init --bare ~/repos/myproject.gitcd /path/to/existing/repogit remote add origin ~/repos/myproject.git# Push main to origingit push origin mainReset, Revert Changes - git reset
Section titled “Reset, Revert Changes - git reset”# "Reset repository to the latest remotegit fetch origingit reset --hard origin/maingit reset --hard origin/master# This example assumes that the remote repo’s name is “origin” and that# the branch named “master”, in the remote repo, matches the currently# checked-out branch in your local repo.
## From https://stackoverflow.com/questions/1146973/how-do-i-revert-all-local-changes-in-git-managed-project-to-previous-state## Revert Local Changes### To revert changes made to your working copy, do this:git checkout .### orgit restore .
### To revert changes made to the index (i.e., that you have added), do this. Warning this will reset all### of your unpushed commits to mastergit reset
### Reset last commit, changed files will be staged but not committedgit reset --soft HEAD~1
### To revert a change that you have committed:git revert <commit 1> <commit 2>
### To remove untracked files (e.g., new files, generated files):git clean -df
### Or untracked directories (e.g., new or automatically generated directories):git clean -fd
# Remove files from git and indexgit rm -r files
# Remove git tracking from root of repositoryrm -rf .gitRemove passwords and sensitive information from a git repository
Section titled “Remove passwords and sensitive information from a git repository”Follow steps in The Easiest Way To Remove Checked In Credentials From A Git Repo using the BFG tool
Example, remove passwords or sensitive information
# Get BFG jar and make sure Java is installed
# Remove passwords and sensitivte information from the repository and commit it
# In a temporary directory, copy the JAR and create a new file called password.txt to store sensitive information you want to remove from the git repo and itshistory
# Make a copy of your repogit clone https://.../myrepo.git
# Change repo historyjava -jar bfg-1.14.0.jar --replace-text passwords.txt myrepo
# Push changesgit reflog expire --expire=now --all && git gc --prune=now --aggressivegit push --all --forceImport an existing git project into a new repository on GitHub
Section titled “Import an existing git project into a new repository on GitHub”Follow GitHub instructions on importing a new project.
Variations to commands are in this example:
# Copy GitHub url of new repository and use it in the following command# Run in existing repository root directorygit remote add main2 https://github.com/justunsix/olympic-app-go.git# Check existing remotesgit remote -v# Push the 'main' branch or whichever branch you want to push to the new repository. 'main2' is the remote branchgit push main2 mainReset and Set Git Proxy - git config
Section titled “Reset and Set Git Proxy - git config”For information from proxy
You may be prompted with a user/password when running git commands, enter your proxy credentials
# Set git proxygit config --global https.proxy https://1.1.1.1:3128git config --global http.proxy http://1.1.1.1:3128
# Reset git proxygit config --global --unset https.proxygit config --global --unset http.proxygit config --unset https.proxyUsing Multiple SSH Private Keys
Section titled “Using Multiple SSH Private Keys”Source: How to Configure Git to Use Specific SSH Private Keys
See the source and bash - How to specify the private SSH-key to use when executing shell command on Git? - Stack Overflow for more options than the ones listed here.
Option: Use SSH Configuration (~/.ssh.config)
Section titled “Option: Use SSH Configuration (~/.ssh.config)”# Set host and specific key you want to useHost github.com HostName github.com User git IdentityFile ~/.ssh/github_personal_key IdentitiesOnly yesOption is using host aliases for multiple identity
Section titled “Option is using host aliases for multiple identity”# Personal GitHub accountHost github-personal HostName github.com User git IdentityFile ~/.ssh/personal_key IdentitiesOnly yes AddKeysToAgent yes # Optional: Add key to agent on first use
# Work GitHub accountHost github-work HostName github.com User git IdentityFile ~/.ssh/work_key IdentitiesOnly yes
# Then use on command line like:# Clone using the 'github-work' alias and associated keygit clone git@github-work:MyCompany/ProjectRepo.git
# Or, update an existing remote's URLgit remote set-url origin git@github-work:MyCompany/ProjectRepo.gitExplanation of configuration
Section titled “Explanation of configuration”- Host: The alias or pattern to match for where git repository is at
- HostName: Real hostname or IP address to connect to.
- User: The remote username (
gitis used for services like GitHub/GitLab) - IdentityFile: The path to the specific private key file to use
- IdentitiesOnly yes: Tells SSH to try the key specified in IdentityFile and keys in the agent, preventing it from trying default key files (like `~/.ssh/idrsa`) which could be the wrong identity.
- AddKeysToAgent yes: If the key has a passphrase, this attempts to add it to a running SSH agent after the first successful authentication, avoiding repeated passphrase prompts.
- Permissions: Ensure your
~/.ssh/config filepermissions are restricted only to your user withchmod 600 ~/.ssh/config
Option: Using the GITSSH_COMMAND Environment Variable, Session Based Change
Section titled “Option: Using the GITSSH_COMMAND Environment Variable, Session Based Change”This option is available in Git version 2.3.0 and later. The
GITSSH_COMMAND environment variable sets the SSH command
that git uses and can use the -i flag to point to a key file to use.
It is useful for temporary changes and scripts.
# Run a single git command using a specific keyGIT_SSH_COMMAND='ssh -i /path/to/private_key -o IdentitiesOnly=yes' git clone user@host:repo.git
# Set the variable for the current shell sessionexport GIT_SSH_COMMAND='ssh -i /path/to/private_key -o IdentitiesOnly=yes'git pullgit push# Unset it later if needed: unset GIT_SSH_COMMANDAs explained above IdentitiesOnly tells SSH the specific IdentityFile
to use and not use the default ones
On Windows OS, use set
set "GIT_SSH_COMMAND=ssh -i C:\path\to\private_key -o IdentitiesOnly=yes"Option: Using the core.sshCommand Git Configuration Setting
Section titled “Option: Using the core.sshCommand Git Configuration Setting”This option is available in Git 2.10.0 and later. It is like setting the GITSSH_COMMAND in the git configuration for a repository or globally.
Per-Repository Configuration
Section titled “Per-Repository Configuration”cd /path/to/your/repogit config core.sshCommand 'ssh -i /path/to/private_key -o IdentitiesOnly=yes'# git commands in this repo use the specified keyThis adds the setting to the repository’s .git/config file.
Configuration During Clone
Section titled “Configuration During Clone”You can set the configuration temporarily for the `clone` command using the `-c` flag, and then optionally make it permanent within the newly cloned repository:
# Clone using the specified keygit clone -c core.sshCommand="ssh -i /path/to/private_key -o IdentitiesOnly=yes" user@host:repo.git new-repo-dir
# Optionally, make it permanent for this repocd new-repo-dirgit config core.sshCommand 'ssh -i /path/to/private_key -o IdentitiesOnly=yes'
# Cloning and setting the core.sshCommand configuration permanently in one commandgit clone -c "core.sshCommand=ssh -i /path/to/private_key -o IdentitiesOnly=yes" user@host:repo.gitIgnoring User SSH Config
Section titled “Ignoring User SSH Config”Sometimes, you might want Git to use the specified command and key while completely ignoring the user’s `~/.ssh/config`. The `-F /dev/null` option (or equivalent on non-Unix systems) can achieve this:
git config core.sshCommand "ssh -i /path/to/private_key -F /dev/null -o IdentitiesOnly=yes"
Only checkout or clone specific files - git sparse-checkout
Section titled “Only checkout or clone specific files - git sparse-checkout”Use case: reduce amount of files tracked or you are only interested in a subset of files in a repository
Recommend option 3 for large repositories
# Option 1: Git clone and sparse-checkout to only clone specific filesgit clone --no-checkout repository_urlcd repository# Enable sparse-checkoutgit sparse-checkout init# Set sparse-checkout patterngit sparse-checkout set directory/i/wantgit checkout branch_name
# Option 2: Git archive a specific directory and extract itgit archive --remote=https://github.com/user/repo.git HEAD:docs | tar -x# docs - the sub directory you want
# Option 3: Partial clone with sparse-checkoutgit clone --filter=blob:none <repository-url># --filter=blob:none - excludes large blobs, useful for a repo with many large files# and minimizes downloads# Alternatively, if only interested in current commits, use --depth 1git clone --depth 1 --filter=blob:none <repository-url>
# Enable sparse-checkoutgit sparse-checkout init# Set sparse-checkout patterngit sparse-checkout set directory/i/want# or with --conegit sparse-checkout set --cone file1.ext file2.ext dir1 sub/dir2git checkout branch_name