How to stash changes git
How to stash changes git
Stashing and Cleaning
Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. The problem is, you don’t want to do a commit of half-done work just so you can get back to this point later. The answer to this issue is the git stash command.
Stashing takes the dirty state of your working directory — that is, your modified tracked files and staged changes — and saves it on a stack of unfinished changes that you can reapply at any time (even on a different branch).
git stash save is not going away any time soon, so don’t worry about it suddenly disappearing. But you might want to start migrating over to the push alternative for the new functionality.
Stashing Your Work
Now you want to switch branches, but you don’t want to commit what you’ve been working on yet, so you’ll stash the changes. To push a new stash onto your stack, run git stash or git stash push :
You can now see that your working directory is clean:
At this point, you can switch branches and do work elsewhere; your changes are stored on your stack. To see which stashes you’ve stored, you can use git stash list :
You can see that Git re-modifies the files you reverted when you saved the stash. In this case, you had a clean working directory when you tried to apply the stash, and you tried to apply it on the same branch you saved it from. Having a clean working directory and applying it on the same branch aren’t necessary to successfully apply a stash. You can save a stash on one branch, switch to another branch later, and try to reapply the changes. You can also have modified and uncommitted files in your working directory when you apply a stash — Git gives you merge conflicts if anything no longer applies cleanly.
The apply option only tries to apply the stashed work — you continue to have it on your stack. To remove it, you can run git stash drop with the name of the stash to remove:
You can also run git stash pop to apply the stash and then immediately drop it from your stack.
Creative Stashing
Creating a Branch from a Stash
This is a nice shortcut to recover stashed work easily and work on it in a new branch.
Cleaning your Working Directory
Finally, you may not want to stash some work or files in your working directory, but simply get rid of them; that’s what the git clean command is for.
Some common reasons for cleaning your working directory might be to remove cruft that has been generated by merges or external tools or to remove build artifacts in order to run a clean build.
This will run the clean command in an interactive mode.
This way you can step through each file individually or specify patterns for deletion interactively.
Команда Git stash. Как прятать изменения в Git
Команда git stash предназначена для того, чтобы поместить текущие изменения, которые вы выполнили в файлах, в отдельное хранилище, и вернуть файлы к исходному состоянию. То есть git stash прячет изменения в файлах и сохраняет эти изменения отдельно, чтобы потом можно было их вернуть.
Для чего нужен git stash
Приведем пример. Например, вы выполнили какие-нибудь изменения в файлах и хотите переключиться на другую ветку, но чтобы там не было ваших текущих изменений. С помощью команды git stash можно спрятать эти изменения. Ваши изменения помещаются в отдельное хранилище — в стек, а вы можете спокойно переключиться на другую ветку.
Всё, что вы прячете с помощью git stash, попадает в отдельный список. Затем вы можете извлекать оттуда то, что вы туда спрятали — ваши «прятанья» (далее по тексту будет использоваться это слово).
Рассмотрим, как пользоваться командой git stash
Git stash
Чтобы спрятать изменения достаточно выполнить команду:
Git stash save
Например, можно сохранить изменения и добавить сообщение — подписать изменения, чтобы потом вспомнить, что именно было спрятано. В качестве сообщения, например, можно написать о том, какие именно изменения выполнены в файлах.
Git stash list
Каждое выполнение git stash или git stash save на самом деле создает отдельный коммит и сохраняет его отдельно (в стек).
Команда git stash list выводит список всех ваших прятаний:
Самые старые «прятанья» отображаются внизу списка, самые свежие сверху. Каждое прятанье имеет идентификатор с номером, например, stash@ <0>
Git stash apply
Команда git stash apply берет самое свежее прятанье ( stash@ <0>) и применяет его к репозиторию. То есть изменения, которые находятся в этом прятанье, применяются к текущему репозиторию. Это похоже на то, как вы применяете патч, только в качестве патча выступает ваше прятанье.
Если вы хотите применить какое-нибудь конкретное прятанье, можно указать его идентификатор:
Git stash pop
Было:
Стало после git stash pop:
Также можно указать идентификатор прятанья:
Git stash show
Команда git stash show показывает, какие изменения содержатся в прятанье.
Показываются изменения в файлах для самого последнего прятанья (для stash@ <0>):
Можно указать идентификатор прятанья, чтобы вывести изменения в нем:
Git stash branch
Команда git stash branch создает новую ветку с последним прятаньем, и затем удаляет последнее прятанье (как git stash pop).
Можно также указать идентификатор прятанья:
Git stash drop
Команда git stash drop удаляет самое последнее прятанье (stash@<0>).
Можно указать идентификатор прятанья, которое нужно удалить:
Git stash clear
Команда git stash clear удаляет все прятанья. Будьте внимательные перед тем, как ее выполнять, чтобы не удалить нужные данные.
git stash
Команда git stash позволяет на время «сдать в архив» (или отложить) изменения, сделанные в рабочей копии, чтобы вы могли применить их позже. Откладывание изменений полезно, если вам необходимо переключить контекст и вы пока не готовы к созданию коммита.
Откладывание кода
Команда git stash сохраняет неподтвержденные изменения (индексированные и неиндексированные) в отдельном хранилище, чтобы вы могли вернуться к ним позже. Затем происходит откат до исходной рабочей копии. Например:
Теперь вы можете вносить изменения, создавать новые коммиты, переключаться между ветками и выполнять другие операции Git. По необходимости отложенные изменения можно будет применить позже.
Отложенные изменения сохраняются в локальном репозитории Git и не передаются на сервер при выполнении команды push.
Применение отложенных изменений
Чтобы применить ранее отложенные изменения, воспользуйтесь командой git stash pop :
При извлечении отложенных изменений они удаляются из набора и применяются к рабочей копии.
Вы также можете применить изменения к рабочей копии, не удаляя их из набора отложенных изменений. Для этого воспользуйтесь командой git stash apply :
Это полезно, если вам нужно применить одни и те же отложенные изменения к нескольким веткам.
Теперь вы умеете выполнять основные операции с отложенными изменениями. Однако необходимо помнить о следующей особенности команды git stash : по умолчанию Git не создает отложенные изменения для неотслеживаемых или игнорируемых файлов.
Откладывание неотслеживаемых или игнорируемых файлов
По умолчанию команда git stash создает следующие отложенные изменения:
При этом следующие файлы отложены не будут:
Поэтому если в приведенный выше пример добавить третий файл — неиндексированный (т. е. без выполнения команды git add ), при выполнении команды git stash этот файл не будет отложен.
Управление несколькими наборами отложенных изменений
Рекомендуем добавлять к отложенным изменениям описание в качестве подсказки. Для этого используется команда git stash save «сообщение» :
По умолчанию команда git stash pop применяет последний набор отложенных изменений: stash@
Если вам нужно применить определенный набор ранее отложенных изменений, укажите его идентификатор в качестве последнего аргумента. Это можно сделать так:
Просмотр различий между наборами отложенных изменений
Частичное откладывание изменений
Нажмите ?, чтобы увидеть полный список команд для работы с участками кода. Часто используются следующие команды:
Команда | Описание |
---|---|
/ | искать участок кода по регулярному выражению |
? | Справка |
n | не откладывать участок кода |
q | выйти (все выбранные участки будут отложены) |
s | разделить участок кода на меньшие части |
y | отложить участок кода |
Специальной команды для прерывания не предусмотрено, но прекратить процесс откладывания можно, нажав CTRL-C (сигнал SIGINT).
Создание ветки из отложенных изменений
Если изменения в ветке отличаются от отложенных изменений, операции извлечения или применения последних могут привести к конфликтам. Вместо этого вы можете создать новую ветку с помощью команды git stash branch и применить отложенные изменения к ней. Это можно сделать так:
Новая ветка создается на основе коммита, изменения в котором использовались при создании набора. Затем к этой ветке применяются извлеченные изменения.
Удаление отложенных изменений
Удалить определенный набор отложенных изменений можно с помощью команды git stash drop :
Следующая команда удаляет все наборы отложенных изменений:
Принцип работы команды git stash
В зависимости от отложенных элементов выполнение команды git stash создает два или три новых коммита. На приведенной выше схеме создаются следующие коммиты:
Ниже показано, как команда git stash шифрует рабочий каталог и раздел проиндексированных файлов в виде коммитов:
Перед откладыванием изменений в рабочем каталоге могут находиться изменения отслеживаемых, неотслеживаемых и игнорируемых файлов. Часть этих изменений также может быть проиндексирована в разделе проиндексированных файлов.
При выполнении команды git stash pop изменения из описанных выше коммитов применяются к рабочей копии и разделу проиндексированных файлов, извлеченный коммит удаляется из журнала ссылок на отложенные изменения, и ссылки в журнале сдвигаются. Извлеченные коммиты не удаляются сразу, но помечаются к удалению в будущем при сборе мусора.
Готовы изучить Git?
Ознакомьтесь с этим интерактивным обучающим руководством.
How to stash changes git
Check your version of git by running
SYNOPSIS
DESCRIPTION
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 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@ <0>is the most recently created stash, stash@ <1>is the one before it, stash@ <2.hours.ago>is also possible). Stashes may also be referenced by specifying just the stash index (e.g. the integer n is equivalent to stash@
COMMANDS
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.
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@ <0>is the latest entry, stash@ <1>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].
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.
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.
OPTIONS
This option is only valid for push and save commands.
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.
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.
This option is only valid for push command.
This option is only valid for push command.
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].
A reference of the form stash@ < >. When no is given, the latest stash is assumed (that is, stash@ <0>).
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.
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:
If you mistakenly drop or clear stash entries, they cannot be recovered through the normal safety mechanisms. However, you can try the following incantation to get a list of stash entries that are still in your repository, but not reachable any more:
How to stash changes git
Check your version of git by running
SYNOPSIS
DESCRIPTION
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 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@ <0>is the most recently created stash, stash@ <1>is the one before it, stash@ <2.hours.ago>is also possible). Stashes may also be referenced by specifying just the stash index (e.g. the integer n is equivalent to stash@
COMMANDS
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.
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@ <0>is the latest entry, stash@ <1>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].
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.
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.
OPTIONS
This option is only valid for push and save commands.
This option is only valid for push and save commands.
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.
This option is only valid for push command.
This option is only valid for push command.
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].
A reference of the form stash@ < >. When no is given, the latest stash is assumed (that is, stash@ <0>).
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.
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:
If you mistakenly drop or clear stash entries, they cannot be recovered through the normal safety mechanisms. However, you can try the following incantation to get a list of stash entries that are still in your repository, but not reachable any more: