Git stash вернуть файлы
Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.
The modifications stashed away by this command can be listed with git stash list , inspected with git stash show , and restored (potentially on top of a different commit) with git stash apply . Calling git stash without any arguments is equivalent to git stash push . A stash is by default listed as "WIP on branchname …", but you can give a more descriptive message on the command line when you create one.
The latest stash you created is stored in refs/stash ; older stashes are found in the reflog of this reference and can be named using the usual reflog syntax (e.g. stash@ is the most recently created stash, stash@ is the one before it, stash@ is also possible). Stashes may also be referenced by specifying just the stash index (e.g. the integer n is equivalent to stash@ ).
What if you're doing more-advanced or more-complicated stuff?
There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":
- You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.
This is the easy case, described above. Run git stash save (or plain git stash , same thing). Check out the other branch and use git stash apply . This gets Git to merge in your earlier changes, using Git's rather powerful merge mechanism. Inspect the results carefully (with git diff ) to see if you like them, and if you do, use git stash drop to drop the stash. You're done!
- You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.
Now you want to keep, or even move, these changes, and apply your stash too.
You can in fact git stash save again, as git stash makes a "stack" of changes. If you do that, you have two stashes, one just called stash —but you can also write stash@ —and one spelled stash@ . Use git stash list (at any time) to see them all. The newest is always the lowest-numbered. When you git stash drop , it drops the newest, and the one that was stash@ moves to the top of the stack. If you had, even more, the one that was stash@ becomes stash@ , and so on.
You can apply and then drop a specific stash, too: git stash apply stash@ , and so on. Dropping a specific stash renumbers only the higher-numbered ones. Again, the one without a number is also stash@ .
If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted stash@ or was it stash@ ? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and cleanup-attempt-in-December means a lot more to me than stash@ . (The git stash command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named WIP on branch .)
(Extra-advanced) You've used git stash save -p , or carefully git add -ed and/or git rm -ed specific bits of your code before running git stash save . You had one version in the stashed index/staging area and another (different) version in the working tree. You want to preserve all this. So now you use git stash apply --index , and that sometimes fails with:
You're using git stash save --keep-index in order to test "what will be committed". This one is beyond the scope of this answer; see this other StackOverflow answer instead.
For complicated cases, I recommend starting in a "clean" working tree first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:
Now you're on a "clean" starting point. Or maybe it goes more like this:
The main thing to remember is that the "stash" is a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The apply operation looks at what the commit changed and tries to repeat it wherever you are now. The stash will still be there ( apply keeps it around), so you can look at it more, or decide this was the wrong place to apply it and try again differently, or whatever.
Any time you have a stash, you can use git stash show -p to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, not the saved index changes that --index restores separately.) The command git stash apply , without --index , just tries to make those same changes in your working tree now.
This is true even if you already have some changes. The apply command is happy to apply a stash to a modified working tree (or at least, to try to apply it). You can, for instance, do this:
You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:
Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.
If you start with a clean tree and are just doing several git apply operations, it's easy to back out: use git reset --hard to get back to the clean state, and change your apply operations. (That's why I recommend starting in a clean working tree first, for these complicated cases.)
Необычное припрятывание
У припрятанных изменений есть несколько дополнительных вариантов использования, которые также могут быть полезны. Первый — это использование довольно популярной опции --keep-index с командой git stash . Она просит Git не только припрятать то, что вы уже добавили в индекс, но одновременно оставить это в индексе.
Другой распространённый вариант, который вы, возможно, захотите использовать — это припрятать помимо отслеживаемых файлов также и неотслеживаемые. По умолчанию git stash будет сохранять только изменённые и проиндексированные отслеживаемые файлы. Если вы укажете опцию --include-untracked или -u , Git также припрячет все неотслеживаемые файлы, которые вы создали. Однако включение этой опции по-прежнему не будет прятать файлы с явным игнорированием; чтобы дополнительно припрятать игнорируемые файлы, используйте --all (или просто -a ).
И наконец, если вы укажете флаг --patch , Git не будет ничего прятать, а вместо этого в интерактивном режиме спросит вас о том, какие из изменений вы хотите припрятать, а какие оставить в вашем рабочем каталоге.
DISCUSSION
A stash entry is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the entry was created. The tree of the second parent records the state of the index when the entry is made, and it is made a child of the HEAD commit. The ancestry graph looks like this:
where H is the HEAD commit, I is a commit that records the state of the index, and W is a commit that records the state of the working tree.
Some final words about --index (what the heck is it?)
What the --index does is simple to explain, but a bit complicated internally:
- When you have changes, you have to git add (or "stage") them before commit -ing.
- Thus, when you ran git stash , you might have edited both files foo and zorg , but only staged one of those.
- So when you ask to get the stash back, it might be nice if it git add s the added things and does not git add the non-added things. That is, if you are add -ed foo but not zorg back before you did the stash , it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.
The --index flag to apply tries to set things up this way. If your working tree is clean, this usually just works. If your working tree already has stuff add -ed, though, you can see how there might be some problems here. If you leave out --index , the apply operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes Git's merge machinery, using the working tree commit in the "stash bag". If you don't care about preserving staged/unstaged, leaving out --index makes it a lot easier for git stash apply to do its thing.
I frequently use git stash and git stash pop to save and restore changes in my working tree. Yesterday I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but git stash pop appears to remove all references to the associated commit.
I know that if I use git stash then .git/refs/stash contains the reference of the commit used to create the stash. And .git/logs/refs/stash contains the whole stash. But those references are gone after git stash pop . I know that the commit is still in my repository somewhere, but I don't know what it was.
Is there an easy way to recover yesterday's stash commit reference?
Note that this isn't critical for me today because I have daily backups and can go back to yesterday's working tree to get my changes. I'm asking because there must be an easier way!
I had this problem. To update my repo, I ran git stash , git pull -r upstream , git push -f origin , git stash pop , and pop said "fatal: log for refs/stash is empty". 😲 I tried a bunch of these answers, nothing worked. When I looked in .git/refs/stash, the SHA was in there. Maybe a problem with marking a Windows network drive for offline sync? 🤷♂️
Suggestion: Avoid using git stash for anything you aren't willing to lose. If it's worth saving, then it's worth making a full commit (possibly on a separate temp branch). With git commit , your "stashes" are much easier to keep track of. For one thing, you can include a commit message. But more relevant to this question, your changes will be accessible in the local reflog -- even if you reset/delete the branch.
COMMANDS
push [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-u|--include-untracked] [-a|--all] [-q|--quiet] [-m|--message ] [--pathspec-from-file= [--pathspec-file-nul]] [--] […]
Save your local modifications to a new stash entry and roll them back to HEAD (in the working tree and in the index). The part is optional and gives the description along with the stashed state.
For quickly making a snapshot, you can omit "push". In this mode, non-option arguments are not allowed to prevent a misspelled subcommand from making an unwanted stash entry. The two exceptions to this are stash -p which acts as alias for stash push -p and pathspec elements, which are allowed after a double hyphen -- for disambiguation.
save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-u|--include-untracked] [-a|--all] [-q|--quiet] []
This option is deprecated in favour of git stash push. It differs from "stash push" in that it cannot take pathspec. Instead, all non-option arguments are concatenated to form the stash message.
List the stash entries that you currently have. Each stash entry is listed with its name (e.g. stash@ is the latest entry, stash@ is the one before, etc.), the name of the branch that was current when the entry was made, and a short description of the commit the entry was based on.
The command takes options applicable to the git log command to control what is shown and how. See git-log[1].
Show the changes recorded in the stash entry as a diff between the stashed contents and the commit back when the stash entry was first created. By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@ to view the second most recent entry in patch form). If no is provided, the default behavior will be given by the stash.showStat , and stash.showPatch config variables. You can also use stash.showIncludeUntracked to set whether --include-untracked is enabled by default.
Remove a single stashed state from the stash list and apply it on top of the current working tree state, i.e., do the inverse operation of git stash push . The working directory must match the index.
Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.
Like pop , but do not remove the state from the stash list. Unlike pop , may be any commit that looks like a commit created by stash push or stash create .
Creates and checks out a new branch named starting from the commit at which the was originally created, applies the changes recorded in to the new working tree and index. If that succeeds, and is a reference of the form stash@> , it then drops the .
This is useful if the branch on which you ran git stash push has changed enough that git stash apply fails due to conflicts. Since the stash entry is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
Remove all the stash entries. Note that those entries will then be subject to pruning, and may be impossible to recover (see Examples below for a possible strategy).
Remove a single stash entry from the list of stash entries.
Create a stash entry (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. This is intended to be useful for scripts. It is probably not the command you want to use; see "push" above.
Store a given stash created via git stash create (which is a dangling merge commit) in the stash ref, updating the stash reflog. This is intended to be useful for scripts. It is probably not the command you want to use; see "push" above.
Припрятывание ваших наработок
Для примера, предположим, что вы перешли в свой проект, начали работать над несколькими файлами и, возможно, добавили в индекс изменения одного из них. Если вы выполните git status , то увидите ваше изменённое состояние:
Теперь вы хотите сменить ветку, но пока не хотите фиксировать ваши текущие наработки; поэтому вы припрячете эти изменения. Для того, чтобы припрятать изменение в выделенное для этого специальное хранилище, выполните git stash или git stash push :
Теперь вы можете увидеть, что рабочая копия не содержит изменений:
В данный момент вы можете легко переключать ветки и работать в любой; ваши изменения сохранены. Чтобы посмотреть список припрятанных изменений, вы можете использовать git stash list :
В данном примере, предварительно были припрятаны два изменения, поэтому теперь вам доступны три различных отложенных наработки. Вы можете применить только что припрятанные изменения, используя команду, указанную в выводе исходной команды: git stash apply . Если вы хотите применить одно из предыдущих припрятанных изменений, вы можете сделать это, используя его имя, вот так: git stash apply stash@ . Если вы не укажете имя, то Git попытается восстановить самое последнее припрятанное изменение:
Как видите, Git восстановил в файлах изменения, которые вы отменили ранее, когда прятали свои наработки. В данном случае при применении отложенных наработок ваш рабочий каталог был без изменений, а вы пытались применить их в той же ветке, в которой вы их и сохранили; но отсутствие изменений в рабочем каталоге и применение их в той же ветке не являются необходимыми условиями для успешного восстановления припрятанных наработок. Вы можете припрятать изменения, находясь в одной ветке, а затем переключиться на другую и попробовать восстановить эти изменения. Также при восстановлении припрятанных наработок в вашем рабочем каталоге могут присутствовать изменённые и незафиксированные файлы — Git выдаст конфликты слияния, если не сможет восстановить какие-то наработки.
Спрятанные изменения будут применены к вашим файлам, но файлы, которые вы ранее добавляли в индекс, не будут добавлены туда снова. Для того, чтобы это было сделано, вы должны запустить git stash apply с опцией --index , при которой команда попытается восстановить изменения в индексе. Если вы выполните команду таким образом, то полностью восстановите ваше исходное состояние:
Команда apply только пытается восстановить припрятанные наработки — при этом они останутся в хранилище. Для того, чтобы удалить их, вы можете выполнить git stash drop , указав имя удаляемых изменений:
Вы также можете выполнить git stash pop , чтобы применить припрятанные изменения и тут же удалить их из хранилища.
What about the very worst possible case?
Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to git stash apply --index , but it's no longer possible to apply the saved stash with --index because the branch has diverged too much since the time you saved it.
This is what git stash branch is for.
- check out the exact commit you were on when you did the original stash , then
- create a new branch, and finally
- git stash apply --index
the attempt to re-create the changes definitely will work. This is what git stash branch newbranch does. (And it then drops the stash since it was successfully applied.)
EXAMPLES
When you are in the middle of something, you learn that there are upstream changes that are possibly relevant to what you are doing. When your local changes do not conflict with the changes in the upstream, a simple git pull will let you move forward.
However, there are cases in which your local changes do conflict with the upstream changes, and git pull refuses to overwrite your changes. In such a case, you can stash your changes away, perform a pull, and then unstash, like this:
When you are in the middle of something, your boss comes in and demands that you fix something immediately. Traditionally, you would make a commit to a temporary branch to store your changes away, and return to your original branch to make the emergency fix, like this:
You can use git stash to simplify the above, like this:
You can use git stash push --keep-index when you want to make two or more commits out of the changes in the work tree, and you want to test each change before committing:
When you are in the middle of massive changes and you find some unrelated issue that you don’t want to forget to fix, you can do the change(s), stage them, and use git stash push --staged to stash them out for future use. This is similar to committing the staged changes, only the commit ends-up being in the stash and not on the current branch.
I had some uncommitted changes in my development branch and I stashed them using git stash , but there were some changes which were very important among those stashed ones. Is there any way to get back those changes?
Also, I have made some changes on top of the stashed code files since.
Is there any chance I can retrieve the stashed changes to a new branch if possible?
No. Actually I am new to git. As I am not fully aware of all the commands i didn't try anything else! I dont wanna lose those changes.
If you dont want lose the stashed changes, try using 'git stash apply'. This will apply the stashed changes to you current branch, while still retaining the stash. If everything is ok, after applying the stash, you can drop the stash, using 'git stash drop'
@robert Thank you for the simple answer as compared to the horribly complicated (for a newbie) accepted answer.
Очистка рабочего каталога
Наконец, у вас может возникнуть желание не прятать некоторые из изменений или файлов в вашем рабочем каталоге, а просто избавиться от них. Команда git clean сделает это для вас.
Одной из распространённых причин для этого может быть удаление мусора, который был сгенерирован при слиянии или внешними утилитами, или удаление артефактов сборки в процессе её очистки.
Вам нужно быть очень аккуратными с этой командой, так как она предназначена для удаления неотслеживаемых файлов из вашего рабочего каталога. Даже если вы передумаете, очень часто нельзя восстановить содержимое таких файлов. Более безопасным вариантом является использование команды git stash --all для удаления всего, но с сохранением этого в виде припрятанных изменений.
Предположим, вы хотите удалить мусор и очистить ваш рабочий каталог; вы можете сделать это с помощью git clean . Для удаления всех неотслеживаемых файлов в вашем рабочем каталоге, вы можете выполнить команду git clean -f -d , которая удалит все файлы и также все каталоги, которые в результате станут пустыми. Параметр -f (сокращение от слова force — заставить) означает принудительное удаление, подчеркивая, что вы действительно хотите это сделать, и требуется, если переменная конфигурации Git clean.requireForce явным образом не установлена в false .
Если вы хотите только посмотреть, что будет сделано, вы можете запустить команду с опцией -n , которая означает «имитируй работу команды и скажи мне, что ты будешь удалять».
По умолчанию команда git clean будет удалять только неотслеживаемые файлы, которые не добавлены в список игнорируемых. Любой файл, который соответствует шаблону в вашем .gitignore , или другие игнорируемые файлы не будут удалены. Если вы хотите удалить и эти файлы (например, удалить все .o -файлы, генерируемые в процессе сборки, и таким образом полностью очистить сборку), вы можете передать команде очистки опцию -x .
Если вы не знаете, что сделает при запуске команда git clean , всегда сначала выполняйте её с опцией -n , чтобы проверить дважды, перед заменой -n на -f и выполнением настоящей очистки. Другой способ, который позволяет вам более тщательно контролировать сам процесс — это выполнение команды с опцией -i (в «интерактивном» режиме).
Ниже выполнена команда очистки в интерактивном режиме.
Таким образом, вы можете просмотреть каждый файл индивидуально или указать шаблоны для удаления в интерактивном режиме.
Существует причудливая ситуация, когда вам, возможно, придется проявить особую настойчивость, попросив Git очистить ваш рабочий каталог. Если вы оказались в рабочем каталоге, в который вы скопировали или клонировали другие репозитории Git (возможно, в виде подмодулей), даже git clean -fd откажется удалить эти каталоги. В таких случаях вам нужно добавить второй параметр -f для акцентирования.
Is it possible to extract a single file or diff of a file from a git stash without popping the stash changeset off?
23 Answers 23
Once you know the hash of the stash commit you dropped, you can apply it as a stash:
Or, you can create a separate branch for it with
After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.
If you have only just popped it and the terminal is still open, you will still have the hash value printed by git stash pop on screen (thanks, Dolda).
Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:
. or using Powershell for Windows:
This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.
The easiest way to find the stash commit you want is probably to pass that list to gitk :
. or see the answer from emragins if using Powershell for Windows.
This will launch a repository browser showing you every single commit in the repository ever, regardless of whether it is reachable or not.
You can replace gitk there with something like git log --graph --oneline --decorate if you prefer a nice graph on the console over a separate GUI app.
To spot stash commits, look for commit messages of this form:
WIP on somebranch: commithash Some old commit message
Note: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did git stash .
Операция stash берет изменённое состояние вашего рабочего каталога, то есть изменённые отслеживаемые файлы и проиндексированные изменения, и сохраняет их в хранилище незавершённых изменений, которые вы можете в любое время применить обратно.
В конце октября 2017 года в списке рассылки Git проходило обширное обсуждение, по итогам которого команда git stash save признана устаревшей в пользу существующей альтернативы git stash push . Основная причина этого заключается в том, что в git stash push есть возможность сохранить выбранные спецификации пути, что не поддерживает git stash save .
Команда git stash save не исчезнет в ближайшее время, поэтому не беспокойтесь о её внезапной пропаже. Но вы можете начать переход на push для использования новой функциональности.
The easy answer to the easy question is git stash apply
Just check out the branch you want your changes on, and then git stash apply . Then use git diff to see the result.
After you're all done with your changes—the apply looks good and you're sure you don't need the stash any more—then use git stash drop to get rid of it.
I always suggest using git stash apply rather than git stash pop . The difference is that apply leaves the stash around for easy re-try of the apply , or for looking at, etc. If pop is able to extract the stash, it will immediately also drop it, and if you subsequently realize that you wanted to extract it somewhere else (in a different branch), or with --index , or some such, that's not so easy. If you apply , you get to choose when to drop .
It's all pretty minor one way or the other though, and for a newbie to Git, it should be about the same. (And you can skip all the rest of this!)
9 Answers 9
On the git stash manpage you can read (in the "Discussion" section, just after "Options" description) that:
A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD when the stash was created.
So you can treat stash (e.g. stash@ is first / topmost stash) as a merge commit, and use:
Explanation: stash@^1 means the first parent of the given stash, which as stated in the explanation above is the commit at which changes were stashed away. We use this form of "git diff" (with two commits) because stash@ / refs/stash is a merge commit, and we have to tell git which parent we want to diff against. More cryptic:
should also work (see git rev-parse manpage for explanation of rev^! syntax, in "Specifying ranges" section).
Likewise, you can use git checkout to check a single file out of the stash:
or to save it under another filename:
(note that here is full pathname of a file relative to top directory of a project (think: relative to stash@ )).
You might need to protect stash@ from shell expansion, i.e. use "stash@" or 'stash@' .
This is pretty cool. I didn't really understand how stash worked until I read your answer (which lead me to the git-checkout addition). I really didn't get that, when you do a stash, git saves TWO commits -- one for the state of the index and one for the state of the working copy which is a merge between the index and the original HEAD. This explains the odd trees I've seen when I visualize the repository with "gitk --all" when stashes are present.
Note that the git checkout approach copies the exact file from the stash -- it doesn't merge it with what's in your working directory like git stash apply would. (So if you have any changes from the base the stash was created on, they'll be lost).
Note that in order for git stash apply to merge the changes in a file that has been modified in the work tree since the file was stashed, that file in the work tree must be staged. For auto-merge to work, the same files cannot be modified both in the working copy and in the stashed copy-to-be-merged. Finally, stash apply doesn't remove the item from stash like git stash pop would.
If you use git stash apply rather than git stash pop , it will apply the stash to your working tree but still keep the stash.
With this done, you can add / commit the file that you want and then reset the remaining changes.
Make sure you put space after the "--" and the file name parameter
Replace zero(0) with your specific stash number. To get stash list, use:
Based on Jakub Narębski's answer -- Shorter version
Edit: See cambunctious's answer, which is basically what I now prefer because it only uses the changes in the stash, rather than comparing them to your current state. This makes the operation additive, with much less chance of undoing work done since the stash was created.
To do it interactively, you would first do
. then open the patch file in a text editor, alter as required, then do
cambunctious's answer bypasses the interactivity by piping one command directly to the other, which is fine if you know you want all changes from the stash. You can edit the stash^! to be any commit range that has the cumulative changes you want (but check over the output of the diff first).
If applying the patch/diff fails, you can change the last command to git apply --reject which makes all the changes it can, and leaves .rej files where there are conflicts it can't resolve. The .rej files can then be applied using wiggle , like so:
This will either resolve the conflict, or give you conflict markers that you'd get from a merge.
If your distro doesn't have wiggle , you can just build it:
Previous solution: There is an easy way to get changes from any branch, including stashes:
You may omit the file spec if you want to patch in many parts. Or omit patch (but not the path) to get all changes to a single file. Replace 0 with the stash number from git stash list , if you have more than one. Note that this is like diff , and offers to apply all differences between the branches. To get changes from only a single commit/stash, have a look at git cherry-pick --no-commit .
Создание ветки из припрятанных изменений
Если вы спрятали некоторые изменения, оставили их на время, а сами продолжили работать в той же ветке, у вас могут возникнуть проблемы с восстановлением наработок. Если восстановление будет затрагивать файл, который уже был изменён с момента сохранения наработок, то вы получите конфликт слияния и должны будете попытаться разрешить его. Если вам нужен более простой способ снова протестировать припрятанные изменения, вы можете выполнить команду git stash branch , которая создаст для вас новую ветку, перейдёт на коммит, на котором вы были, когда прятали свои наработки, применит на нём эти наработки и затем, если они применились успешно, удалит эти припрятанные изменения:
Это удобное сокращение для того, чтобы легко восстановить припрятанные изменения и поработать над ними в новой ветке.
6 Answers 6
OPTIONS
This option is only valid for push and save commands.
All ignored and untracked files are also stashed and then cleaned up with git clean .
When used with the push and save commands, all untracked files are also stashed and then cleaned up with git clean .
When used with the show command, show the untracked files in the stash entry as part of the diff.
This option is only valid for the show command.
Show only the untracked files in the stash entry as part of the diff.
This option is only valid for pop and apply commands.
Tries to reinstate not only the working tree’s changes, but also the index’s ones. However, this can fail, when you have conflicts (which are stored in the index, where you therefore can no longer apply the changes as they were originally).
This option is only valid for push and save commands.
All changes already added to the index are left intact.
This option is only valid for push and save commands.
Interactively select hunks from the diff between HEAD and the working tree to be stashed. The stash entry is constructed such that its index state is the same as the index state of your repository, and its worktree contains only the changes you selected interactively. The selected changes are then rolled back from your worktree. See the “Interactive Mode” section of git-add[1] to learn how to operate the --patch mode.
The --patch option implies --keep-index . You can use --no-keep-index to override this.
This option is only valid for push and save commands.
Stash only the changes that are currently staged. This is similar to basic git commit except the state is committed to the stash instead of current branch.
The --patch option has priority over this one.
This option is only valid for push command.
Pathspec is passed in instead of commandline args. If is exactly - then standard input is used. Pathspec elements are separated by LF or CR/LF. Pathspec elements can be quoted as explained for the configuration variable core.quotePath (see git-config[1]). See also --pathspec-file-nul and global --literal-pathspecs .
This option is only valid for push command.
Only meaningful with --pathspec-from-file . Pathspec elements are separated with NUL character and all other characters are taken literally (including newlines and quotes).
This option is only valid for apply , drop , pop , push , save , store commands.
Quiet, suppress feedback messages.
This option is only valid for push command.
Separates pathspec from options for disambiguation purposes.
This option is only valid for push command.
The new stash entry records the modified states only for the files that match the pathspec. The index entries and working tree files are then rolled back to the state in HEAD only for these files, too, leaving files that do not match the pathspec intact.
For more details, see the pathspec entry in gitglossary[7].
This option is only valid for apply , branch , drop , pop , show commands.
A reference of the form stash@> . When no is given, the latest stash is assumed (that is, stash@ ).
Читайте также: