Git Snippets
Source: Git - Documentation
# 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
# Create a new branchgit checkout -b new-branch-name# make changes to new-branch-name# Merge changes to main branchgit checkout maingit merge new-branch-name
# Checkout an existing branchgit checkout my-branch
# List all git branches, local, and remotes in current repositorygit branch -a
# Check differences between local "main" branch and remotegit diff main remotes/origin/HEAD
# List branchesgit branch -a -v
# Switch to git (remote) branch named "Release_3.0"git switch Release_3.0
# Remove temporary branch named "list"git branch -d list
# Go back to last branchgit checkout -
# 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
# 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
# Git worktrees - manage multiple working trees## Like managing a git branch as a separate directory## Like manually git cloning a repo to a separate directory and changing the working branch of that repo## Easier to keep track of separate branches
# Create a new branch whose name is the final part of the command; add a new worktree with a feature branchgit worktree add ../myrepo-newfeature new-feature## Example## /bubbles is [master]## /bubbles-table is branch [use-lipgloss-table]
# Create new worktree with existing branch maingit worktree add ../repo-main main
# If you want to make experimental changes or do testing without disturbing development,# it is often convenient to create a throwaway worktree not associated with any branch.# Creates a new worktree with a detached HEAD at the same commit as the current branch examplegit worktree add -d ../repo-experimental
# List work trees, their location, and checked out branchesgit worktree list
# Remove a worktreegit worktree remove worktree-name
# 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
# Example workflow with these branches:# - main / master# - pull request review# - feature developmentgit clone myrepo.git # maincd myrepogit worktree add ../myrepo-feature feature_branchgit worktree add ../myrepo-pr pull_request_numbered_branch
# 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 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"## Complete work in other branch, then open 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 trueCreate a new repository
Section titled “Create a new repository”#1: Create a folder for this project on your local hard drive$ mkdir my-project
#2: change into this folder$ cd my-project
#3: initialize a new, empty Git repository here$ git init
...after having written some code + created some files...#4: add all changes to the next (= first) commit$ git add .
#5: create this first commit$ git commit -m "Initial commit"
# git command and add filesgit commit -am"message"Create 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.gitgit push origin masterReset, Revert Changes
Section titled “Reset, Revert Changes”# "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
### 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
Section titled “Reset and Set Git Proxy”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 yes-
Option is using host aliases for multiple identity
~/.ssh/config # Personal GitHub accountHost github-personalHostName github.comUser gitIdentityFile ~/.ssh/personal_keyIdentitiesOnly yesAddKeysToAgent yes # Optional: Add key to agent on first use# Work GitHub accountHost github-workHostName github.comUser gitIdentityFile ~/.ssh/work_keyIdentitiesOnly 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.git -
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 GITSSHCOMMAND Environment Variable, Session Based Change
Section titled “Option: Using the GITSSHCOMMAND Environment Variable, Session Based Change”This option is available in Git version 2.3.0 and later. The
GITSSHCOMMAND 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 GITSSHCOMMAND in the git configuration for a repository or globally.
-
Per-Repository Configuration
Terminal window 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
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:
Terminal window # 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.git -
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
Section titled “Only checkout or clone specific files”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