Git

Git

Reference for working with Git.

Installing git

For macOS install git using Homebrew

brew install git

Getting help

Show a list of basic commands, all (-a) commands or help for a specific command

git help
git help -a
git help <command>

Display the man page for a command

man git-<command>

Display the current installed version of git

git --version

Working with git

Creating a repository

Create a new git repository in the current directory

Create a bare git repository (bare repositories don't have a working directory of files)

Status

Show a summary of the state of working directory and index

Show status including ignored files

Show a list of all merged branches

Staging files

Add a specific file to the index, add all files . or add interactively -i

Interactive add allows selective staging, unstaging of changed files as well as partial commits of specific lines.

Partial commits can be created by choosing the patch option and then specifying split to further refine chunks. After exiting interactive adding, you need to the commit the index.

Stage all tracked / changed files

Add all files in the current repository

Add parts of the changes with each file (interactively add)

Open the current diff in text editor

Removing files from the index

Removing a file from the index (unstaging files)

Unstage all files from the index

Undoing local file changes

Discard local changes to a modified, unstaged file

Discard local changes for all modified, unstaged files

Remove newly added, but previously uncommitted, file from staged file list Only affects index not file

Clean up untracked files

Show which files or files and directories that git clean will remove

Remove untracked files or both files and directories

Committing changes

Commit current staged index

Commit current staged index, opening default editor to enter commit message

Verbose commit, include a diff of the commit in the commit message

Adjust the last commit

Resetting Commits

Reset allows you to change the repository and working directory to a known state Allows altering a combination of the HEAD, index and working directory depending on the mode used

Soft updates only the HEAD pointer

Mixed (default) updates the HEAD pointer and the index

Hard moves the HEAD pointer, update the index and update the working directory

Removing and renaming files

Stage an existing tracked file for removal (Removal occurs when committed). Git checks if the file being removed has any unsaved changes. It notifies you if it does and doesn't remove it

To force the removal of a file that has unsaved changes

Rename file1 to file2 (Move occurs when committed)

Force overwrite of file2 with file1

Show the full log history for a file that has been renamed. Without --follow, the log stops at the rename point

Tracking empty directories

Git will not track empty directories. To commit empty directories add a blank file to the directory. By convention a common empty filename is .gitkeep

If the directory contents are not intended to be version controlled use the following .gitignore rules to track the directory (via .gitkeep) and ignore all other files within the directory. This is useful for directories intended for transient files like logs

Git repository history

View history log

Show the commit log for the current branch

Show the commit log for the named branch

Show the commit log for the specified file or directory

Use a double dash -- to separate a file to act on from the settings to use

Set the output format for the commit summary (Options: oneline, short, full)

Abbreviate the commit hash so that it is shorter

Output the diff patches for each commit along with the details

Output statistics about each commit eg. the files affected and the number of lines changed

Output an graphical representation of the commits and branches

Show the last number of specified commits in the log eg. git log -5 shows the last 5

Combine the above eg. show a log of all commits with a graphical output of timeline

Search commit messages for the search string

Search the commit message for the author name

Return commits where the search string was part of a files edit (known as pickaxe) eg. git log -Sdiv (returns all commits where the string 'div' formed part of an addition or deletion)

Output the log for the specified range. Since and until are any valid identifiers such has relative or absolute history reference or sha1 identifier

Output difference between current branch HEAD and origin/main

After a merge, use --merge with log to show only the commits from files that relate to the merge conflict

Shows < in the log if a commit is from the left side of a merge (target / ours), and > if it is from the right (source / theirs)

Show commits more recent than a specific date. Date can be formatted date or human readable (eg. "3 days ago")

Show commits older than a specific date. Date can be formatted date or human readable (eg. "3 days ago")

Show log history for a set of lines using absolute or relative ranges

Show details about commits, tags, branches & files

Show details of the latest commit

Show details of a specific commit

Show details of a commit relative to the current state

Show details about a specific tag

Show details about the latest commit on another branch

Show contents of file on another branch

Show the commit hash for any reference input

List the files tracked in the git repo. Add -s to show all files with SHA1 hashes. Add -u to show only conflicted files

Additional commit references, ranges and symrefs

As well as dates, parameters and sha1 references, the following features are available for referencing points in history.

Reference a parent commit (if multiple parents exist, eg. following a merge, use ^1, ^2, ^3 etc)

Show the first parent of HEAD

Show the second parent of HEAD

Reference the next ancestor in the history (~1 is the parent, ~2 is the grandparent etc), eg. To specify the last 50 commits on branch main: main~50

Current branch, diff between commits 2 and 3 times back

Specifies the range of commits between commit1 and commit2, any method of specify a commit may be used

The set of commits that are reachable from either commit1 or commit2, but not both

The most recent commit of the current branch

The saved state before an operation is performed, allows comparing before and after or rollback

A temporary reference to the last branch fetched, only available immediately after a fetch operation

A temporary reference to the head of the branch that is being merged in

Git blame and diff

Using Blame to find who edited what

Show blame details for a file

Show blame output for a set of lines using absolute or relative ranges

Comparing changes using diff

Diff shares many of the same commands, flags and options as log

Diff local working directory against current index (staged files), exposing what is dirty in the working directory

Diff showing further granularity of changes within lines

Diff index (staged files) against HEAD (current repo state)

Diff local working directory against HEAD (current repo state)

Diff between the working directory state and the state at the named commit

Diff between the staged state and the named commit state

Diff current branch against another branch

Diff only the named file (use -- if there is any confusion between file names and tag names)

Diff between any tree objects within the commit graph, the working directory or the index. A tree object can be referenced by commit id, branch name, tag or any valid identifier method

Show the diff between the current state and the state prior to the latest commit (see what changed due to the last commit)

Return on diff results that include the as a changed item (-S is also called pickaxe)

Show the stats for the diff (number of lines changed, added and removed)

Example: Show stats for the state at commit1 and commit2, limiting to files in the named directory

List the file names affected and their change status

List the number of lines affected and the file names

Show only the file names of the files affected

Set the number of context lines to surround the diff output with to lines before and after

Output the diff result as a patch file eg. file.patch (for use with git apply)

Flags for diff

Detect renames and show only the rename rather than the full add and removal of the file

Ignore whitespace differences in files

Include statistics about the diffs (number of lines changed, number added, number removed)

Sample diff output

Working with branches and tags

Show the current branches

Show a list of local branch names

Show a complete list of branch names, including remote branches

Create a new branch

Create a branch new branch

Create a branch name with a suffix. Used for convenience in organising branches. Allows wild carding actions against the suffix to affect all sub branches etc

Start a branch at a commit other than the current state

Delete an existing branch

Deletes a branch (issues a warning if changes exist on the branch that haven't been merged)

Force the deletion of a branch even if there are unmerged changes

Delete a remote branch

Alternative delete remote branch syntax

Show stale remote branches from local (branches deleted from origin, which still exist locally)

Remove stale remote branches from local

Renaming branches

Rename a local branch

Rename an existing branch (-m merges current branch entirely into the new branch)

Delete the original branch

Relocate any existing branch pointer to a reference a new commit

Switching branches

Switch to a branch

Create and switch branches in one step. Allows moving unstaged work directly to the new branch

If you have uncommitted changes on the current branch, you can't switch to a new branch if there is a conflict. Specifying -m merges your current changes into the branch being switched to (without creating a commit).

Show a summary of the branch commits

Show recent commits for local branches

Show recent commits for all branches including remotes

Show activity for only the specified branches, can be used with the wildcard suffix

Example of wildcard usage and having a suffix, allows showing all branches of a suffix type (eg. bug/*)

Merging branches

Conflicted files from a merge contain standard merge markers (<<<<<<<, =======, >>>>>>>) to show each version. Manually correct the file, remove the markers until the file is in a state that you are happy with then add and commit

Merge a specified branch into the current branch

Merge a specified branch from a remote into the current branch

Switch to the specified branch and merge in the contents of the current branch (merge only occurs on filesystem, no commit is made)

Switch to the specified branch and discard current branch changes

Abort a merge (any time before committing) and return to the state of the branch before initiating the merge

Abort a merge (after committing) and return to the state prior to merging (any dirty working directory files will be lost)

Show details of the conflicted files from the merge

Shows a combined output with merge markers, using double column for showing lines added, removed and modified from both sources

Compare the merge output to the original working directory

Compare the merge output to the version being merged in

Combined set of changes since the merge base

Show the commits that contribute to the merge conflict and the changes they introduced for . Omit for all.

For merge commits, git log and git show include some additional information about the merge. A line labelled Merge: <ancestor1 sha> <ancestor2 sha> shows the origin of the merges. The files conflicted by the merge are listed in the commit and the diff is a combined diff.

Determine the commit at which the branch was created from the original branch

Apply the merge as a single squashed commit, destroying the source branches commit history in the target branch

Resolve conflicts by selecting wholesale our version (--ours), or their version (--theirs)

Check out a single file from another branch into the current branch

Revert branch state

Revert local branch to upstream origin state

Rebase branch

Rebase takes the current branch, sets it to state of the target branch specified, the 'replays' all the branch change sets over the top.

Create and manage tags

List tags

Create a new tag at the current point

Create a new tag at the specified commit

Delete tag

Checkout tag (update the working directory to reflect the history at the tag)

Git Stash

Stash working directory changes

Stash away current Index (Staged files)

Stash with message

Restore stashed changes (keeps the stash in the stash list)

List current stashes

Remove the most recent stash

Drop the specified stash eg. git stash drop stash@{0}

Clear all stashes

Apply specific stash eg. git stash apply stash@{0}

Apply stash to a new branch

Create and apply patches

Apply the patch file to the current working directory

Remote repositories

Working with remote repositories

Clone a remote repository to the local file system

Clone a remote repository that requires a username

Clone a remote repository without the history (retrieves the latest code version)

Clone a remote repository to a given depth

Note: Repos created with depth limit cannot be recloned into new repos, but they are good for quick checkout and development

Pull changes from remote repo

Push current branch Pushing a local branch to a non-existant remote branch name will create the remote branch

Push all branches (including new)

To push and pull from specific remote repositories with the current active local branch

Push current branch and set it to automatically track the named remote branch

For example, to push to origin main and set your current branch to track main

Assign the current branch to track the named remote branch

Assign the current branch to track the named remote branch

Show the name of the remote repository

Show details of the remote repo and status of branch tracking

Show full details of connected remote repositories

Checkout and automatically add tracking for a branch in a remote repo

Create a remote entry in .gitconfig for a remote called (labelled) , located at

Allows: git push , to push a branch to the remote

Create a bare clone (no working directory) of an existing git repo. Useful when housing a bare repo on a remote server (use <reponame>.git as folder name)

Fetch upstream changes from origin or a named upstream without merging

Configuring push behaviour

git config push.default allows defining what git push will do

Using git config push.default current will only push the current active branch to it's tracking remote instead of pushing all tracked branches

Config to set up a repository to only push to its own remote branch with git push

Config to set up all repositories to only push to its own remote branch

Setting upstream

Git and SVN

Working with SVN repositories

Clone an SVN repository

Show details about the SVN repository

Pull in the latest changes from the SVN repo (Stash before rebase)

Push git commits back to SVN (Stash before dcommit if working directory is dirty)

Squash several commits from another branch into one commit on the current branch

Useful git SVN commands

Show the SVN ignore file output

Append the SVN ignore info to the git exclude file

Create a .gitignore file based on the SVN ignore output

The git-svn-id that is included in the log info of each commit reveals the upstream repo, branch and commit info. This is the svn area dcommits will get pushed to.

Git Bisect

Finding where an error was introduced with Bisect

Note: Always start bisect with a clean working directory

Initiate bisect, and set the 'bad' (present failing state) and 'good' (earlier known working state) points

Initiate bisect mode

Find the commit where the error occurs (usually HEAD), and assign it as bad

Find a commit (ideally close by) where the state is working and assign it as good

Git will now halve the distance between the bad and good commit and update the working directory to that commit.

Test the code to determine if it's good or bad, then issue the appropriate command

If the error is still present in the new version

If the error is not present in the new version

Continue until git narrows down the selection to the single commit where the error was introduced

Other bisect commands:

To skip a commit, if it's not testable for whatever reason

Show the history of the commits checked and the good / bad state they were assigned

Open an editor to visually inspect the remaining commits

Return the working directory to the original state before bisect commenced

To correct a mistake in your bisect choices, copy the output of bisect log to a new text file and edit the lines to change good / bad. Then use git bisect replay, pointing to this modified log file to replay the steps to recommence bisecting

Hooks

Hooks are executable shell scripted files that reside in .git/hooks/ and are triggered when their named action occurs

List hook related commands and options for git

Combining projects with submodules

To include another git project inside your existing project, use git submodule

  • All submodule commands must be run from the project root directory.

  • Files from submodules are not added or cloned along with the project, only the details of what the submodule is and how to recreate it.

  • Details of the submodule location in the project and the submodules git clone source are contained in a generated file called .gitmodules.

  • .gitmodules forms part of the project and will be included in clone operations so other uses can use git submodule commands to import submodules.

Add another git repository as a submodule to the current project in the named directory. A file called .gitmodules will be created in the project root directory of the parent project that lists the path and repo url details.

Add the submodule references from .gitmodules into .git/config to allow the project to perform submodule update. If you wish to locally reference another repo (eg. local test repo), you can edit .git/config and modify the repo target details for the submodule

Update current submodules inside the repository with the relevant files from their own repositories

Show the commits that the included repository submodules point to

A file that contains the location and source of the submodule repositories. This file is passed around with the project to allow others to update submodule files.

Advanced Management

Note: The following commands rewrite history and should be used with caution on published repos and pushed commits

Cherry Pick

Cherry pick a specified commit onto the current checkout out commit

Rewrite history

Rewrite history correcting email address for git author

Rewrite history correcting author name for git author

Remove file references from git history

Configuring Git

Show configuration

List applied configuration values (later settings override earlier)

Show where git configuration is set

List specific configuration field value (eg. email)

Configuration files

Local configuration overrides general configuration

Local config for specific repository (git config <settings>)

User config for all repositories (git config --global <settings>)

System wide config for all repositories and all users (git config --system <settings>)

Using the config command to apply and remove settings

Set committer name and email for all git repositories

While inside a git repo, set the committer name and email for just that repository

Remove config field for current repo / context (eg. email)

Configuration for setting ignore rules

To ignore files (.gitignore) may be placed in any directory, this allows fine grained control over ignore rules. If you don't want to commit your ignore files into the repo, use the repo ignore or add .gitignore to be ignored. Alternatively, add and commit the .gitignore file to include it in the repo and allow others to receive and use the files.

Order of precedence for ignore file hierarchy:

  • .gitignore (current directory)

  • .gitignore (parent directories)

  • .git/info/ignore (repo wide ignore rules)

  • .gitignore file specified by core.exclude file directive (user / system wide ignore rules)

Allows the ignore file to become part of the repo so other people cloning get the same ignore settings

Flags for ignore rules

Reverse an earlier ignore rule eg. !<pattern> allows the pattern if it was ignored higher up the hierarchy

Wild cards can be used

Example pattern for matching files to ignore

Items with a hash at the start are comments in the ignore file

Directories to ignore end with a slash

Example ~/.gitconfig

Example ~/.gitignore

Collaborating over the local network

To collaborate with your team, you can allocate a machine to act as a central server, just like SVN. However, there are lots of benefits to using the distributed features of git to collaborate directly between individual developers. For this you'll want to allow access to your git repos.

If you want to establish an interim git repository that others will share, and you will push to, you can use the following steps to set up a git user with git-shell access for collaborators to use. The limitation of this approach is that it treats all users as having the same privileges. More fine grained control requires the use of a system like Gitolite or Gitosis for local / behind firewall repos, or GitHub for public / private, externally hosted repos.

Setting up a git user for sharing on OS X

Remote login needs to be enabled

Create a new Git User

Give the user a name and password (in the following examples we'll using git as the user name)

After choosing "Create Account", right click on the new account from the Account list on the left and choose "Advanced Options".

For the login shell above, enter the path to the git-shell command.

MacPorts: /opt/local/bin/git-shell

Homebrew: /usr/local/bin/git-shell

Now we can remove all the extra files OSX creates by default in a git users home directory. Make absolutely sure you are in the new user directory before using rm.

Copy (or create) your bare git repos to the root of /Users/git, and set the owner to be git

You can now clone from this repo from another machine or location on your computer

Working with external tools

Pipe output from any command into VS Code (or another text editor)

A visual view of the commit graph showing the repository history, commits and branches

Start and detach instance of gitk

Utility Commands

Clean up and compact repo

Generating summary reports for a repository

Git statistics commands

Show all commit messages, grouped together by user

Show total commit count per user

Show total number of files changed, lines inserted and deleted

Checkout GitHub pull request branch locally

In your .gitconfig file add the following fetch rule to your origin configuration:

To check out a particular pull request (eg. pr/999)

Good git GUI clients

Last updated