Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git: Can I stash an untracked file without adding it to the index?

A related question How do you stash an untracked file? was answered with "track the file." This doesn't work for my particular needs, however.

I'm trying to stash everything that isn't in the index with git stash save --keep-index so that I can validate the index in my pre-commit hook. The idea is from the "Testing partial commits" example of the git-stash man page. I want to make sure that what I'm actually committing passes the tests and not just whats in the working directory. Here's what I have so far:

echo "Running tests on the staging area."
git stash save --keep-index
# configure, build, run tests, clean
git stash pop; true

This seems to work until I have untracked files in my working directory which don't get stashed. Some searching resulted in a feature request from two years ago: Option to save untracked and/or ignored files in stash, but nothing else.

Should I be using stash at all? Perhaps theres a better way involving temporary branches or something.

like image 719
James Marble Avatar asked Jul 16 '10 21:07

James Marble


People also ask

Can you git stash untracked files?

By default, git stash will stash only modified and staged tracked files. If you specify --include-untracked or -u , Git will include untracked files in the stash being created.

Do I need to git add before stash?

You have to add the untracked files of the repository by using the “git add” command and run the “git stash” command to save the untracked file and clean the current directory for working by removing the untracked file from the repository folder.

Do untracked files get committed?

Most untracked files will be staged and committed. Others will simply be ignored by including them in the . gitignore file. However, some files and directories will remain untracked, and in certain instances it can be useful to delete these untracked files from your Git repo.


2 Answers

As I answered on the related question, the answer is now YES:

As of git 1.7.7, git stash accepts the --include-untracked option to include untracked files in your stash.

git stash --include-untracked

Or you can use the short -u option.

git stash -u
like image 81
John Kary Avatar answered Sep 24 '22 22:09

John Kary


No, git stash will only "record the current state of the working directory and the index". So stashing won't pickup your untracked files.

Switching to a temporary branch and tracking the untracked files there, as you suggest, seems like a reasonable approach.

like image 33
David Underhill Avatar answered Sep 22 '22 22:09

David Underhill