[Git 2] Practical Git Commands and Tips: stash, add -p, insteadOf

Commands for comparing HEAD with a given commit, and two branches, shown on a commit graph

Written by

in

The basic Git flow (clone → add → commit → push) is covered in Git basics. This post is the next step: commands you use every day but whose options you can never remember when you need them, grouped by situation. Use it as a cheat sheet and look up only what you need.


Working with remote branches

git fetch --all --prune          # get the latest from all remotes (and clean up deleted remote branches)
git branch -r                    # list remote branches
git branch -a                    # list local + remote branches

git switch -c mytest --track origin/mytest   # check out a remote branch as a local branch
# (older way) git checkout -t origin/mytest

git clone -b dev --single-branch <repository URL>   # clone only one branch
git branch -m <old name> <new name>                 # rename a local branch

💡 git remote update does almost the same as git fetch --all. To also clean up branches deleted on the remote from your local list, add --prune.


Comparing branches, files and commits

Commands for comparing HEAD with a given commit, and two branches, shown on a commit graph
Figure 1. A..B means "commits that are in B but not in A". log, rev-list and diff all use the same notation.
# list of files changed between two branches
git diff --name-status main dev
git diff --name-status dev                # compare the current branch with dev

# compare one file between two branches (path after -- with a space)
git diff main..dev -- rtl/fifo.sv

# change history of one file, including content
git log -p -- rtl/fifo.sv

To compare the current commit (HEAD) with a given commit:

git rev-list --count <commit>..HEAD          # how many commits have piled up since
git log --oneline <commit>..HEAD             # which commits they are
git diff --name-only <commit>..HEAD          # changed file names only
git diff --name-status <commit>..HEAD        # files + kind of change (A/M/D)
git show -s --format=%ci <commit>            # the time of that commit

Taking just one file from another branch

Sometimes you want only a specific file without merging the whole branch.

git checkout dev -- rtl/fifo.sv         # overwrite with dev's version of the file
git checkout -p dev -- rtl/fifo.sv      # pick, asking for each changed part (hunk)
# Git 2.23 and later: git restore --source=dev -- rtl/fifo.sv

stash: putting work aside for a moment

If you git pull or switch branches while you have uncommitted changes, you get conflicts or Git refuses. Put the changes into a temporary store (stash) first.

git stash push -m "refactoring FIFO"    # save with a description (older: git stash save "...")
git stash list                          # stash@{0}, stash@{1}, ... list
git pull                                # or git switch other-branch
git stash pop                           # restore the latest stash + remove it from the list
Command What it does
git stash apply Restores the latest stash but keeps it in the list
git stash apply stash@{2} Restores a specific stash
git stash apply --index Restores the staged state as well
git stash pop Restore + remove from the list (apply + drop)
git stash drop stash@{1} Deletes a specific stash
git stash show -p stash@{0} Shows what is in a stash

⚠️ If pop hits a conflict, the stash is not deleted; it stays in the list. Resolve the conflict, then run git stash drop yourself.


Committing only part of a change (git add -p)

When you did two things in one file but want separate commits, -p (--patch) lets you stage changed parts (hunks) one by one.

git add -p rtl/fifo.sv

Git shows each hunk and asks.

Key Meaning
y Add this hunk
n Skip this hunk
s Split the hunk into smaller pieces
e Edit by hand to add only some lines
a Add this hunk and all remaining hunks in this file
d Skip this hunk and all remaining hunks in this file
q Quit (keeps what you picked so far)

Check what was added with git diff --staged, then commit.


Removing files

git rm old.sv                    # remove from both the repository and the working directory
git rm -r old_dir/               # a folder
git rm --cached big.log          # remove from the repository only and keep the file (when adding to .gitignore)

# files listed in a list file, all at once (safe with names containing spaces)
xargs -d '\n' git rm --cached < filelist.txt

A readable log with an alias

Register aliases in ~/.gitconfig so you do not have to type long options every time.

[alias]
    g    = log --graph --all --abbrev-commit --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %s %C(dim white)— %an%C(reset)%C(bold yellow)%d%C(reset)'
    slog = log --stat --abbrev-commit
$ git g
*   bfc067a - (7 minutes ago) Merge branch 'feature-analysis' — Alex Kim (HEAD -> main)
|\
| * c834b93 - (28 minutes ago) Add RTL analysis step — Alex Kim (feature-analysis)
* | 6389e6f - (32 minutes ago) Add filelist generator — Sam Lee (feature-filelist)
|/
* 499c795 - (34 minutes ago) Initial commit — Alex Kim

8-digit commit hashes

Hashes are shown shortened to 7 digits by default. If you put the commit hash into a 32-bit register (for example a chip's version register), 8 digits (8 hex digits = 32 bits) is more convenient.

[core]
    abbrev = 8          # applies to every command

To use it for one command only, pass it as an option, as in git log --abbrev=8.


Graphical tools for diff and merge

VS Code as the diff and merge tool

[diff]
    tool = vscode
[difftool "vscode"]
    cmd = code --wait --diff $LOCAL $REMOTE
[merge]
    tool = vscode
[mergetool "vscode"]
    cmd = code --wait --merge $REMOTE $LOCAL $BASE $MERGED
git difftool main          # opens a VS Code diff window per file
git difftool -d main       # compares whole folders at once

Diffs and conflict resolution with Meld

Meld, popular on Linux, has an intuitive 3-way view that is especially good for resolving conflicts.

[diff]
    tool = meld
[difftool "meld"]
    cmd = meld "$LOCAL" "$REMOTE"
[merge]
    tool = meld
[mergetool "meld"]
    cmd = meld "$LOCAL" "$MERGED" "$REMOTE" --output "$MERGED"
[alias]
    mdiff = difftool -d
git mdiff dev              # compare the current branch with dev by folder
git mdiff main dev         # compare two branches
git mergetool              # opens a Meld window per conflicting file
Meld 3-way merge view: LOCAL on the left, MERGED in the middle, REMOTE on the right, with arrows to apply changes
Figure 2. The git mergetool view. Click the arrows on the left (your branch) or right (the incoming branch) to apply changes to the result in the middle, or edit the middle directly, then save.

With several conflicting files, Meld windows open one after another, one per file. Once all are saved, finish the merge with git commit. If the leftover *.orig backup files bother you, set git config --global mergetool.keepBackup false.


Two basic settings

Default branch name main

Repositories created on GitLab or GitHub default to main, but a local git init may create master.

git config --global init.defaultBranch main   # repositories created from now on (Git 2.28 or later)
git branch -m master main                     # a repository already created

Changing the commit message editor

Without extra settings, Ubuntu opens commit messages in nano. The most reliable way to switch to an editor you know is to set it directly in Git.

git config --global core.editor vim
git config --global core.editor "code --wait"   # VS Code

Without core.editor, Git looks at the environment variables GIT_EDITOR → VISUAL → EDITOR in that order, and falls back to the system default editor. To change Ubuntu's system default, use sudo update-alternatives --config editor.


Rewriting repository addresses: insteadOf

Sometimes you have to use a workspace made of many repositories at another site or on a mirror server. If the original server address is written in config files (manifests) or submodules, editing every one is tedious. With url.<new address>.insteadOf, Git rewrites the beginning of the address automatically when it connects.

# use the mirror server for addresses that start with git@old-server.example.com:
git config --global url."ssh://git@mirror.example.com:2222/".insteadOf "git@old-server.example.com:"

git config --global --get-regexp '^url\.'      # check
git config --global --unset url."ssh://git@mirror.example.com:2222/".insteadOf   # remove

To use a different address only for push, use pushInsteadOf. For setting up a mirror server, see the mirroring part of Running a self-hosted GitLab.


What should you record when bringing in files from another repository?

When you copy part of another project's code, leave a trail so the source can be traced later.

  • Make the import a commit on its own. Changes go in the following commits.
  • Write the original repository address and the original commit hash in the commit message.
  • If you already pushed without that information, record it in an annotated tag.
git commit -m "Import AXI bridge from common-ip

Source: <original repository URL>
Commit: 3f2a9c1e"

Summary

Situation Command
Use a remote branch git switch -c X --track origin/X
Compare a file between two branches git diff A..B -- path
Just one file from another branch git checkout B -- path (pick with -p)
Put work aside for a moment git stash push -m → git stash pop
Commit only part of a change git add -p
Graphical diff and conflict resolution git difftool -d, git mergetool
Rewrite server addresses url.<new>.insteadOf <original>

Further reading

Git (5 posts)

  1. Git Basics: From Installation to Branches, Conflicts and Merge Requests
  2. Practical Git Commands and Tips: stash, add -p, insteadOf Reading now
  3. Tidy Commit Messages with Gitmoji: the 20 Most Used
  4. Managing Large Binaries with Git LFS
  5. Exchanging Changes with diff and patch, Including the -p Option

See the full Tech Notes index

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *