Git Reference ยท Environment Variables
GIT_INDEX_FILE
Reference for GIT_INDEX_FILE: point Git at a different index so scripts can build trees and commits without disturbing the staging area.
The index (staging area) is a file, .git/index. Almost every command that touches it reads and writes that one path. GIT_INDEX_FILE names a different file, so a command works against a separate, throwaway staging area while your real one stays exactly as it was.
This is the building block for scripts that need to assemble a tree in a scratch index: creating a commit from selected files without disturbing what you have staged, deploying a subset of a branch, or reading another branch's tree to inspect it. Many Git commands do this internally.
GIT_INDEX_FILE=/tmp/scratch.index git read-tree HEAD
GIT_INDEX_FILE=/tmp/scratch.index git add some-file
GIT_INDEX_FILE=/tmp/scratch.index git write-tree
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
GIT_INDEX_FILE=<path> git <command>
| Name | Description |
|---|---|
GIT_INDEX_FILE |
Path of the index file to read and write instead of $GIT_DIR/index. Relative paths are relative to the directory where Git runs. |
Edge cases: if the file does not exist, Git treats it as an empty index and creates it on first write. An index copy needs the object database of the repository to stay valid, so keep the scratch file inside the same repository (for example under .git/). Git writes the new index through a lock file named <path>.lock, which must be creatable next to it.
Usage notes
- Pattern:
read-tree(orread-tree --empty) to seed,addorupdate-indexto change,write-treeto turn it into a tree,commit-treeto wrap the tree in a commit. Exactly whatgit commit --onlyandgit stashdo behind the scenes. GIT_INDEX_FILEis inherited by children, including hooks and any commands you pipe into. Unset it when you are done, or limit it to one command, as the first example does.- Hooks can be affected: during
git commit -aor--only, Git runs thepre-commithook withGIT_INDEX_FILEpointing at a temporary index so the hook sees the files that will really be committed. Hooks that invoke other Git commands should respect it rather than reset it. - Sparse and worktree setups: each linked worktree has its own index; this variable overrides it for one command.
- A working tree is still involved.
git addwith a scratch index reads files from the working tree, which is why the second example can addnotes.txt.git checkout-indexandgit read-tree -uwrite to the working tree, so use them with care.