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
# 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>
# 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"
# 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 pathgit worktree add <path>## Example## /bubbles is [master]## /bubbles-table is branch [use-lipgloss-table]
# Create new worktree with existing branch examplegit 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 treesgit-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
# Submodules - clone, initialize all submodules and update each submodule in the repositorygit clone --recurse-submodules https://github.com/chaconinc/MainProject
Create 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 master
Reset, Revert Changes
Section titled “Reset, Revert Changes”# "Reset repository to the latest remotegit fetch origingit 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 .git
Remove 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 --force
Import 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 main
Reset 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.proxy
Using 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 (
git
is 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 file
permissions are restricted only to your user withchmod 600 ~/.ssh/config
Option: Using the GITSSHCOMMAND Environment Variable
Section titled “Option: Using the GITSSHCOMMAND Environment Variable”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_COMMAND
As 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 -c core.sshCommand="ssh -i /path/to/private_key -o IdentitiesOnly=yes" clone 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