Git reflog
The git reflog command is used for Git to record updates made to the tip of branches. It allows to return to commits even to the ones that are not referenced by any branch or any tag. After rewriting history, the reflog includes information about the previous state of branches and makes it possible to go back to that state if needed.

There are some git commands, to which a reference specifying parameter or a “ref” can be applied. This parameter serves to point to a commit. With the help of this reflog mechanism, you can keep track of the update time of git refs in the local repository.
The basic usage of git reflog command
Generally git reflog is used like the following:
It is the shortcut of this:
The command above outputs the HEAD reflog . The output looks like the following:
Reflog references
Be default, git reflog outputs the reflog of the HEAD reference, which is considered to be an iconic reference to the branch, which is currently active. You can access a git ref by using the [email protected]
Execute the following command for getting the entire reflog of all the references:
Pass the current branch name to git reflog show , if you want to see the reflog for it. In the example below displays a reflog for the test_branch branch.
Using the command below will output a reflog for a git stash:
Timed reflogs
There is an attached timestamp to each reflog entry.They can be leveraged as a qualifier which is token of Git ref pointer syntax. This allows to filter Git reflogs by time. Here are some examples of time qualifiers:
- 1.minute.ago
- 1.hour.ago
- 1.day.ago
- yesterday
- 1.week.ago
- 1.month.ago
- 1.year.ago
- 2011-05-17.09:00:00
You can also have a combination of time qualifiers (e.g. 1.week.3.hours.ago), and plural forms (e.g. 5.hours.ago). The refs of time qualifiers can be given to other git commands, like this:
Here we will have a diff of the current master branch against master 1 week ago.
Subcommands of git reflog
There exist some arguments, considered to be subcommands, that are accepted by git reflog . These subcommands are presented below.
Show — git reflog show subcommand
The git reflog show subcommand is an alias for git log -g —abbrev-commit —pretty=oneline . It is passed by default. In the following example, the two commands are equivalent to each other:
Expire — git reflog expire subcommand
The git reflog expire subcommand is used for cleaning old or unapproachable reflog entries. The danger of this subcommand is the possibility of data loss. In fact, the expire subcommand is not used by users. It is used only by the Git. By default, the reflog date of expiry is set to 90 days. Pass —expire=time argument to git reflog expire for specifying an expire time.
Delete — git reflog delete subcommand
The git reflog delete subcommand is designed for deleting passed reflog entries. However, the end users avoid executing this subcommand, because, as in the case of git reflog expire , there is a risk of data loss.
Recovering lost commits
Actually, commits are never being lost in Git, even during history rewriting operations. Let’s see an example of a git log —pretty=oneline that looks like this:
Now suppose we commit some new changes to this repository and run the following:
As a result, the log now looks like this:
At this stage, in order to make an interactive rebase against the master branch, we need to execute the following:
While rebasing, the s rebase subcommand marks commits for squashing into the most recent «API changes» commit. As a result of squashing the commits, the git log output now has a look, like this:
It now seems that commits marked for squashing are no longer there. If you need to operate on a squashed commit, you can leverage the reflog.
There are reflog entries for the start and finish of the rebase and preceding those is the «API changes» commit. The reflog ref can be passed to git reset in order to reset a commit before the rebase.
This command will move HEAD to that commit with «API changes», and restore the other squashed commits.
git reflog
На этой странице подробно рассматривается команда git reflog . Git отслеживает изменения в конце веток с помощью механизма журналов ссылок (reflog). Многие команды Git принимают параметр ссылки (ref), которая является указателем на коммит. Ниже представлены распространенные примеры таких команд:
- Git checkout
- git reset
- git merge
Журналы ссылок позволяют отслеживать время обновления ссылок Git в локальном репозитории. Кроме журналов ссылок для последних коммитов ветки, существует специальный журнал ссылок команды git stash. Журналы ссылок хранятся в подкаталогах внутри каталога .git локального репозитория. Для размещения каталогов git reflog используются пути .git/logs/refs/heads/. и .git/logs/HEAD , а также .git/logs/refs/stash (если в репозитории использовалась команда git stash ).
Общий обзор команды git reflog приводится в документе Страница «Переписывание истории». В этом документе рассматриваются расширенные возможности конфигурации git reflog , частые примеры и трудности использования git reflog , отмена изменений с помощью команды git reflog и многое другое.
Основное назначение
Журнал ссылок используется главным образом для вызова следующих данных:
Это ярлык, эквивалентный следующей команде:
С помощью этой команды вызывается журнал ссылок HEAD . Вывод команды должен выглядеть примерно так:
Другие распространенные примеры использования журнала ссылок см. на странице Переписывание истории.
Ссылки из журнала ссылок
По умолчанию команда git reflog выводит журнал ссылок для указателя HEAD . Указатель HEAD является символической ссылкой на активную в данный момент ветку. Имеются журналы ссылок и для других указателей. Для обращения к ссылке в Git используется синтаксис name@
Для вызова полного журнала ссылок выполните следующую команду:
Чтобы просмотреть журнал ссылок для конкретной ветки, передайте имя этой ветки команде git reflog show :
С помощью этого кода выводится журнал ссылок для ветки otherbranch . В следующем примере подразумевается, что изменения были отложены ранее с помощью команды git stash .
С помощью этого кода выводится журнал ссылок для git stash. Полученные указатели можно передавать другим командам Git:
С помощью этого кода выводится результат применения команды git diff, которая выполняет сравнение изменений stash@ <0>относительно указателя otherbranch@ <0>.
Журналы ссылок с заданным сроком действия
К каждой записи журнала ссылок привязана метка времени. Эти метки можно использовать в качестве токена qualifier в синтаксисе указателя на ссылку Git, чтобы фильтровать журналы ссылок Git по времени. Ниже в качестве примеров приводится несколько префиксов времени:
- 1.minute.ago
- 1.hour.ago
- 1.day.ago
- yesterday
- 1.week.ago
- 1.month.ago
- 1.year.ago
- 2011-05-17.09:00:00
Префиксы времени можно комбинировать (например, 1.day.2.hours.ago ). Кроме того, возможно использование форм множественного числа (например, 5.minutes.ago ).
Указатели префиксов времени можно передавать другим командам Git.
В этом примере выполняется сравнение актуальной главной ветки с главной веткой по состоянию на 1 день назад. Эту функцию удобно использовать для просмотра изменений за определенный период времени.
Подкоманды и параметры конфигурации
В команде git reflog можно использовать несколько дополнительных аргументов, которые имеют статус подкоманд.
Просмотр: git reflog show
По умолчанию аргумент show передается неявным образом. Так, команда
Кроме того, git reflog show является псевдонимом команды git log -g —abbrev-commit —pretty=oneline . При выполнении команды git reflog show отобразится журнал для переданного элемента .
Истечение срока действия: git reflog expire
Подкоманда истечения срока действия удаляет устаревшие или недоступные записи из журнала ссылок. Выполнение подкоманды expire может привести к потере данных. Обычно она не применяется пользователями и является внутренней подкомандой Git. При передаче параметра -n или —dry-run команде git reflog expire выполняется тестовый прогон, который выводит записи журнала ссылок, помеченные для удаления, но на самом деле не удаляет их.
По умолчанию срок действия журнала ссылок составляет 90 дней. Время окончания срока действия можно указать, передав аргумент командной строки —expire=time команде git reflog expire или настроив конфигурацию Git с именем gc.reflogExpire .
Удаление: git reflog delete
Функция подкоманды delete очевидна. Эта подкоманда удаляет переданную запись журнала ссылок. Как и в случае с подкомандой expire , использование delete может привести к потере данных. Обычно она также не вызывается пользователями.
Восстановление потерянных коммитов
Данные в Git не теряются даже при выполнении таких операций переписывания истории, как перебазирование или исправление коммита. Представим, что в репозиторий внесены новые изменения. При этом вывод команды git log —pretty=oneline имеет следующий вид:
Мы отправляем эти изменения и выполняем следующий код:
С появлением нового коммита журнал теперь имеет следующий вид:
На данном этапе выполним интерактивное перебазирование для главной ветки. При этом используем следующую команду:
В ходе перебазирования мы отметим коммиты, подлежащие склеиванию, с помощью подкоманды перебазирования s . Выполняя перебазирование, мы произведем склеивание нескольких коммитов в последнем коммите под названием «some WIP changes».
После склеивания коммитов вывод команды git log примет следующий вид:
При анализе git log видно, что на данном этапе больше нет коммитов, отмеченных для склеивания. Но что делать, если необходимо обработать один из склеенных коммитов, например удалить связанные с ним изменения из истории? Для этого можно использовать журнал ссылок.
Как можно заметить, в журнале ссылок имеются записи, соответствующие запуску и окончанию команды rebase , а перед ними находится коммит «some WIP changes». Мы можем передать указатель журнала ссылок команде git reset и сбросить данные до точки перед перебазированием.
При выполнении команды сброса указатель HEAD переместится на коммит, в котором были добавлены изменения под названием «some WIP changes». При этом будут восстановлены другие склеенные коммиты.
Резюме
В этом обучающем руководстве была рассмотрена команда git reflog . При этом были описаны некоторые ключевые моменты:
- Просмотр журнала ссылок для конкретных веток
- Отмена команды git rebase с помощью журнала ссылок
- Определение и просмотр записей журнала ссылок с метками времени
Мы кратко рассмотрели использование git reflog с другими командами Git, такими как git checkout, git reset и git merge. Дополнительные сведения см. на страницах этих команд. Более подробную информацию о ссылках и журнале ссылок см. здесь.
Git reflog что это
This command manages the information recorded in the reflogs.
Reference logs, or «reflogs», record when the tips of branches and other references were updated in the local repository. Reflogs are useful in various Git commands, to specify the old value of a reference. For example, HEAD@ <2>means «where HEAD used to be two moves ago», master@
The command takes various subcommands, and different options depending on the subcommand:
The «show» subcommand (which is also the default, in the absence of any subcommands) shows the log of the reference provided in the command-line (or HEAD , by default). The reflog covers all recent actions, and in addition the HEAD reflog records branch switching. git reflog show is an alias for git log -g —abbrev-commit —pretty=oneline ; see git-log[1] for more information.
The «expire» subcommand prunes older reflog entries. Entries older than expire time, or entries older than expire-unreachable time and not reachable from the current tip, are removed from the reflog. This is typically not used directly by end users — instead, see git-gc[1].
The «delete» subcommand deletes single entries from the reflog. Its argument must be an exact entry (e.g. » git reflog delete master@ <2>«). This subcommand is also typically not used directly by end users.
The «exists» subcommand checks whether a ref has a reflog. It exits with zero status if the reflog exists, and non-zero status if it does not.
OPTIONS
Options for show
git reflog show accepts any of the options accepted by git log .
Options for expire
Process the reflogs of all references.
By default when —all is specified, reflogs from all working trees are processed. This option limits the processing to reflogs from the current working tree only.
Prune entries older than the specified time. If this option is not specified, the expiration time is taken from the configuration setting gc.reflogExpire , which in turn defaults to 90 days. —expire=all prunes entries regardless of their age; —expire=never turns off pruning of reachable entries (but see —expire-unreachable ).
Prune entries older than <time> that are not reachable from the current tip of the branch. If this option is not specified, the expiration time is taken from the configuration setting gc.reflogExpireUnreachable , which in turn defaults to 30 days. —expire-unreachable=all prunes unreachable entries regardless of their age; —expire-unreachable=never turns off early pruning of unreachable entries (but see —expire ).
Update the reference to the value of the top reflog entry (i.e. <ref>@<0>) if the previous top entry was pruned. (This option is ignored for symbolic references.)
If a reflog entry’s predecessor is pruned, adjust its «old» SHA-1 to be equal to the «new» SHA-1 field of the entry that now precedes it.
Prune any reflog entries that point to «broken commits». A broken commit is a commit that is not reachable from any of the reference tips and that refers, directly or indirectly, to a missing commit, tree, or blob object.
This computation involves traversing all the reachable objects, i.e. it has the same cost as git prune. It is primarily intended to fix corruption caused by garbage collecting using older versions of Git, which didn’t protect objects referred to by reflogs.
Do not actually prune any entries; just show what would have been pruned.
Print extra information on screen.
Options for delete
git reflog delete accepts options —updateref , —rewrite , -n , —dry-run , and —verbose , with the same meanings as when they are used with expire .
Git Reflog — How To Recover A Deleted Branch That Was Not Merged
“Have you ever lost a branch, whose source code was not yet merged in the ‘release’ branch or the ‘main’ branch? What if you want to regenerate a deleted branch though its work has already been merged into the main branch?”. Well, the only solution to such scenarios is Git Reflog.
Through this article on Git Reflog, I will help you understand the scenarios in which your work on a branch could be lost and how to recover the branch. Also, this article will highlight the approach you could take to prevent the unintended loss of a branch while working in a large project.
- What is Git Reflog?
- How and when a branch gets deleted?
- Recover a deleted branch
- What work is restored when the deleted branch is recovered?
- Git Reflog Sub-commands
So, let us get started with this article.
Consider a scenario, a maintainer has to merge many feature branches from different collaborators and then delete them eventually; but the branch is deleted accidentally before the work could be merged?
Well, before I move on this article, let me tell you that it is not possible in Git. Git commands are secure and act as a check post; would not allow you to do so. So, this is where Git Reflog comes into the picture.
What is Git Reflog?
The ‘reflog’ command keeps a Reference logs such as the commit snapshot of when the branch was created or cloned, checked-out, renamed, or any commits made on the branch are maintained by track of every single change made in the references (branches or tags) of a repository and keeps a log history of the branches and tags that were either created locally or checked out. Git and listed by the ‘reflog’ command.
Note: The branch will be recoverable from your working directory only if the branch ever existed in your local repository i.e. the branch was either created locally or checked-out from a remote repository in your local repository for Git to store its reference history logs.
command: git reflog
This command has to be executed in the repository that had the lost branch. If you consider the remote repository situation, then you have to execute the reflog command on the developer’s machine who had the branch.
Now that you know, what is Git Reflog, let us try to delete both a merged and an un-merged branch and see how Git handles that?
Step 1: List the branches that are merged into master
First, check out into the ‘ master ‘ branch if you are on some other branch using the command: