Error bad signature 0x00000000 fatal index file corrupt git

I have not been able to update my repository because I'm getting this error below when I commit the project. I have been told to remove the index file and run these commands del .gitindexand git ...

I have not been able to update my repository because I’m getting this error below when I commit the project.

I have been told to remove the index file and run these commands del .gitindexand
git reset however there no index file in my project file (see below my project file)

Any idea how can I fix this error?

error

9:44 AM Commit failed with error
                0 files committed, 13 files failed to commit: Jobly Version 1.0
                Jobly Version 1.1
                Jobly Version 2.0
                Jobly Version 2.1
                bad signature 0x00000000
                index file corrupt

my project folder
I cannot see the index.file

enter image description here

enter image description here

miken32's user avatar

miken32

41.1k16 gold badges106 silver badges148 bronze badges

asked May 25, 2020 at 15:01

Alfonso Angulo's user avatar

Alfonso AnguloAlfonso Angulo

4041 gold badge7 silver badges15 bronze badges

8

problem: bad signature 0x00000000

solved this error in just 2 commands:

  1. rm -f .git/index
  2. git reset

answered Jun 14, 2021 at 18:31

Farshe's user avatar

1

If you’re using git worktrees, the steps wont work, as the file isn’t located at .git/index. It’s located in the parent repo, at ./git/worktrees/[child name]/index. Delete that file.

answered Aug 14, 2020 at 8:36

Ash's user avatar

AshAsh

1,9161 gold badge14 silver badges15 bronze badges

2

Might to erase a folder on PC, clone the project from GitHub and it solved me. Git log also has been restored in this way.

answered Aug 15, 2022 at 20:37

Vitalii Mytenko's user avatar

Содержание

  1. [Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git
  2. Error Description :
  3. Solution 1:
  4. Solution 2:
  5. Solution 3:
  6. Solution 4:
  7. Solution 5:
  8. Related Searches to How to resolve “Error: bad index – Fatal: index file corrupt” when using Git
  9. git bad signature index file corrupt #648
  10. Comments
  11. Как решить «Ошибка: неверный индекс — Фатальный: поврежден индексный файл» при использовании Git
  12. Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git
  13. 14 ответы

[Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git

Error Description :

  • After git init, if we add and commit a few files, make some changes, add and committed. Set up the git daemon (running under Cygwin on WinXP) and clone the repository once, We get this error with the cloned repository:
click below button to copy the code. By Git tutorial team
  • Is there any way to fix this, other than getting a new copy of the repository?

Solution 1:

  • If the problem is with the index as the staging area for commits (i.e. .git/index ), we can simply remove the index (make a backup copy if we want), and then restore index to version in the last commit:
  • On OSX/Linux:
click below button to copy the code. By Git tutorial team
click below button to copy the code. By Git tutorial team
  • (The reset command above is the same as git reset —mixed HEAD )
  • We can alternatively use lower level plumbing git read-tree instead of git reset.
  • If the problem is with index for packfile you can recover it using git index-pack .

Solution 2:

  • We could try the following to get (possibly?) more information:
click below button to copy the code. By Git tutorial team

Solution 3:

  • This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Solution 4:

  • Clone a new copy of the repo elsewhere
  • Copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Solution 5:

click below button to copy the code. By Git tutorial team

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

git bad signature index file corrupt #648

Often vim-fugitive corrupts my git index. This happens when I call Gstatus and then I add the same file more the one with — . Any one else has this problem?

The text was updated successfully, but these errors were encountered:

Next time it happens take a look inside the index file and see if the contents of the :Gstatus window have overwritten it.

@giuse88 @tpope not sure if this is related, but on the latest version of vim-fugative after I wq to save a commit I get this error: and then this shows up .

If I use vim to check .git/index I see:
using nano I see:

Sounds like an issue with whatever this «BufSurf» plugin is.

On Thu, Jun 25, 2015 at 10:54 AM cj notifications@github.com wrote:


Reply to this email directly or view it on GitHub
#648 (comment).

this is the plugin https://github.com/ton/vim-bufsurf. It only just started happening after I updated fugitive. I guess something changed that bufsurf doesn’t like.

If you can figure out the exact commit that triggered it I can further advise.

i’m having the same issue when doing Gcommit then I added a file to stage. After that, I did another Gcommit, this time with a the message and I got this error.

@tpope so I’m still having this issue. I no longer have that plugin, but after I commit I’m still getting this:

After I do a :Gwrite then :Gcommit type in my message and then :wq this buffer just pops up.

So the commit message buffer closes and then this opens in a split? That’s odd. It looks like a failed attempt to open :Gstatus , which is what happens when you call :Gcommit with no changes.

Can you check the value of :echo b:fugitive_commit_arguments before you :wq ?

Yes. Strange, there definitely was a commit with changes before I did :wq ‘d.

here’s the value: —cleanup=strip -F /home/cj/apps/acd/autolink/.git/COMMIT_EDITMSG —no-edit —no-interactive —no-signoff

While the commit message is still open, try running the following in another window:

Check for errors, and the exit status ( echo $? ).

I’ve run into this (pretty consistently). I’ve tried the troubleshooting
steps without seeing much different than reported above. That said I
think I might have found a workaround (and thus a pointer) My (less then
full perusal) of the code shows that the commit window is normally set
with bufhidden=bdelete but on commit it’s set to bwipeout . It
looks like some path allows that to get skipped. After a commit I can
still see the hidden .git/index file with ls! If I switch to the file at
that point (either directly or by invoking Gstatus) I see the garbled
binary index.

To clarify a bit:

  1. I use Gtatus. Everything is good
  2. I commit a change with Gcommit
  3. At that point I can still see the .git/index file with ls!
  4. If switch to the window, it’s garbled
  5. If I close that window and re-invoke Gstatus, it’s back to expected.

If I bwipeout the buffer directly ( :[BNUMBER]bwipeout ) then
Gstatus and cousins work fine.

The workaround (and possible clue) is that I typically use ZZ as a wq
shortcut. In after/gitcommit.vim I’ve now set a function + mapping that
calls bwipeout and the problem goes away (aka I remap ZZ)

Hoping this is useful 🙂

@cj I have the same issue with garbled text after GCommit command. Have you managed to fix it somehow?

Is anyone here who is having this issue, using vim-airline by any chance?

@yevhen-m I noticed that the issue with fugitive goes away when I uninstall vim-airline, so perhaps that plugin could be the cause of the issue but I’m not entirely sure.

I’m having the same issue… Any fix available?

Hello, I can confirm that this is related to airline. I hit this after switching to Xenial (the exact same setup was working fine on 15.10).

Here is my .vimrc file

/.vim/bundle/Vundle.vim call vundle#begin() » alternatively, pass a path where Vundle should install plugins «call vundle#begin(‘

/some/path/here’) » let Vundle manage Vundle, required Plugin ‘gmarik/Vundle.vim’ » Add all your plugins here (note older versions of Vundle used Bundle instead » of Plugin)* » Auto-Complete Bundle ‘Valloric/YouCompleteMe’ » Folding Plugin ‘tmhedberg/SimpylFold’ «Folding » Python autodindent Plugin ‘vim-scripts/indentpython.vim’ » Indent python » Syntax Plugin ‘scrooloose/syntastic’ «Syntax checker » Plugin ‘nvie/vim-flake8’ » PEP8 » Colors Plugin ‘jnurmine/Zenburn’ » Zenburn theme (console) Plugin ‘altercation/vim-colors-solarized’ «Solarized theme (GUI) Plugin ‘scrooloose/nerdtree’ «Hierarchy tree Plugin ‘kien/ctrlp.vim’ » Search files Plugin ‘vim-airline/vim-airline’ «Status bar Plugin ‘vim-airline/vim-airline-themes’ Plugin ‘tpope/vim-fugitive’ » Show git branch in status bar Plugin ‘xolox/vim-misc’ » Needed by vim-session Plugin ‘xolox/vim-session’ » Make use of mksession easier Plugin ‘saltstack/salt-vim’ » For saltstack files Plugin ‘fatih/vim-go’ » Go Plugin Plugin ‘pearofducks/ansible-vim’ » Ansible plugin Bundle ‘Rykka/riv.vim’ » All of your Plugins must be added before the following line call vundle#end() » required filetype plugin indent on » required set encoding=utf-8 » Set filetype based on name autocmd BufRead,BufNewFile *Dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *.spec.in setlocal filetype=spec autocmd BufRead,BufNewFile *.functions setlocal filetype=sh autocmd BufRead,BufNewFile *.sls setlocal filetype=sls autocmd BufRead,BufNewFile *.jinja setlocal filetype=jinja «» General section set nowrap » don’t wrap lines set tabstop=4 » a tab is four spaces set backspace=indent,eol,start » allow backspacing over everything in insert mode set autoindent » always set autoindenting on set copyindent » copy the previous indentation on autoindenting set shiftwidth=4 » number of spaces to use for autoindenting set shiftround » use multiple of shiftwidth when indenting with ‘ ‘ set showmatch » set show matching parenthesis set ignorecase » ignore case when searching set smartcase » ignore case if search pattern is all lowercase, » case-sensitive otherwise set smarttab » insert tabs on the start of a line according to » shiftwidth, not tabstop set hlsearch » highlight search terms set incsearch » show search matches as you type set history=1000 » remember more commands and search history set undolevels=1000 » use many muchos levels of undo set wildignore=*.swp,*.bak,*.pyc,*.class set visualbell » don’t beep set noerrorbells » don’t beep » FX button mapping set pastetoggle= » Toggle PASTE mode » Remove trailing whitespaces :nnoremap :let _s=@/ :%s/s+$//e :let @/=_s :nohl :unlet _s set hidden » Allow leaving a buffer with unsaved changes set mouse=a » Use mouse in all mode set guioptions-=T «remove toolbar » Completion in menu bar set wildmode=longest,list,full set wildmenu «» Remap » sv sources .vimrc nnoremap sv :source $MYVIMRC :runtime! plugin/settings/* :redraw :echo $MYVIMRC ‘reloaded’ » Buffer navigation nnoremap :bp nnoremap :bn » Split navigations nnoremap l nnoremap h nnoremap k nnoremap j » Copy to system clipboard Visual selection » vnoremap y/ «* «» Folding » Enable folding set foldmethod=indent set foldlevel=99 » See the docstring when folding let g:SimpylFold_docstring_preview=1 » Autocompletion stuff let g:ycm_autoclose_preview_window_after_completion=1 map g :YcmCompleter GoToDefinitionElseDeclaration » Colors set if has(‘gui_running’) set background=dark colorscheme solarized set guifont=DejaVu Sans Mono for Powerline 9 else «colors theme configuration (console) if &term == «linux» || &term == «screen.linux» set t_Co=8 colorscheme zenburn else set t_Co=256 colorscheme zenburn endif endif «» NerdTree let NERDTreeIgnore=[‘.pyc$’, ‘

$’] «ignore files in NERDTree map :NERDTreeToggle » Close vim if only NerdTree is open autocmd bufenter * if (winnr(«$») == 1 && exists(«b:NERDTree») && b:NERDTree.isTabTree()) | q | endif » Always enable status bar set laststatus=2 » Use powerline font symbols let g:airline_powerline_fonts = 1 if !exists(‘g:airline_symbols’) let g:airline_symbols = <> endif let g:airline_symbols.space = «ua0″ » Enable the list of buffers let g:airline#extensions#tabline#enabled = 1 » Session let g:session_autosave = «prompt» let g:session_autosaveperiodic = 60 let g:session_persist_colors = 0 let g:session_persist_font = 0″>

As long as I keep the vim-airline plugin, if I edit a file, :Gwrite, :Gcommit, I end up with a window with the .git/index content like this
DIRC�������CX/�� yada yada

The title of the window being «/.git/index» [Preview]
I can just close it but it’s rather annoying

As long as I remove vim-airline plugin, this does not happen anymore

Using previous version of vim-airline has lead nowhere so far, but still checking

Источник

Как решить «Ошибка: неверный индекс — Фатальный: поврежден индексный файл» при использовании Git

После git init этого я добавил и зафиксировал несколько файлов, внес некоторые изменения, добавил и зафиксировал. Установите демон git (работает под Cygwin на WinXP) и клонировали репозиторий один раз. Теперь я получаю эту ошибку с клонированным хранилищем:

Есть ли способ исправить это, кроме получения новой копии хранилища?

Если проблема связана с индексом в качестве промежуточной области для фиксации (то есть .git/index ), вы можете просто удалить индекс (сделать резервную копию, если хотите), а затем восстановить индекс до версии в последнем коммите:

(Команда reset выше такая же как git reset —mixed HEAD )

В качестве альтернативы вы можете использовать более низкий уровень сантехники git read-tree вместо git reset .

Если проблема связана с индексом для packfile , вы можете восстановить его, используя git index-pack .

Возможно, вы случайно повредили файл .git / index с помощью sed в корне вашего проекта (возможно, рефакторинг?) Примерно так:

чтобы избежать этого в будущем, просто игнорируйте двоичные файлы с помощью вашего grep / sed:

У меня была эта проблема, и я пытаюсь исправить это:

НО это не сработало. Решение ? По какой-то причине у меня были другие папки .git в подкаталогах. Я удаляю эти .git папки (не главные) и git reset снова. Как только они были удалены, все снова заработало.

Это звучит как плохой клон. Вы можете попробовать следующее, чтобы получить (возможно?) Больше информации:

Поскольку вышеприведенные решения оставили меня с постоянными проблемами, я использовал это скучное решение:

  1. клонировать новую копию репо в другом месте
  2. скопируйте новый каталог .git в (поврежденный) репозиторий, содержащий изменения, которые я хотел зафиксировать

Сделал трюк. Кстати, я сделал sed в корне проекта, как и предполагал @hobs. Выучил мой урок.

Это сработало для меня. Хотя мне любопытно, почему я начал получать ошибки в первую очередь. Когда я вышел из системы вчера, это было нормально. Войдите сегодня утром, это не было.

Примечание для пользователей подмодулей git — решения здесь не будут работать для вас как есть.

Допустим, у вас есть dev , например, родительский репозиторий , а ваш субмодульный репозиторий называется api .

если вы внутри, api и вы получите ошибку, упомянутую в этом вопросе:

error: bad index file sha1 signature fatal: index file corrupt

index Файл НЕ будет внутри .git папки. Фактически, это .git даже не будет папка — это будет текстовый документ с расположением реальных данных .git для этого хранилища. Скорее всего как то так

/dev/api $ cat .git gitdir: ../.git/modules/api

Итак, вместо этого rm -f .git/index вам нужно будет сделать это:

rm -f ../.git/modules/api/index git reset

или, в более общем плане,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index git reset

Источник

Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git

После git init , Я добавил и зафиксировал несколько файлов, внес некоторые изменения, добавил и зафиксировал. Настройте демон git (работающий под Cygwin на WinXP) и один раз клонируйте репозиторий. Теперь я получаю эту ошибку с клонированным репозиторием:

Есть ли способ исправить это, кроме получения новой копии репозитория?

задан 12 июля ’09, 08:07

Это в клонированном репозитории или в исходном репозитории? Выдала ли команда clone какие-либо ошибки? — CB Bailey

14 ответы

Если проблема связана с индексом как область подготовки коммитов (т.е. .git/index ), вы можете просто удалить индекс (сделать резервную копию, если хотите), а затем восстановить индекс до версии в последней фиксации:

( reset команда выше такая же, как git reset —mixed HEAD )

Вы также можете использовать более низкий уровень водопровод git read-tree вместо git reset .

Если проблема в индекс для пакетный файл, вы можете восстановить его, используя git index-pack .

Я случайно сделал :w! в :Gstatus (из fugitive.vim). Этот ответ избавил меня от необходимости тянуть за волосы. — Лоуренс Гонсалвес

Я знаю, что нам не нравятся сообщения «мне тоже» — но «мне тоже». Эквивалент в Windows erase /s .gitindex , Мне нужен был erase .gitindex.lock тоже. — Джереми МакГи

Привет, у меня была такая же проблема с поиском и заменой, но git reset сообщает мне, что в .git / objects / pack / есть два файла пакета, к которым нет доступа. У тебя есть идея? — эпсилоны

не было бы безопаснее использовать git reset —keep вместо? в Шпаргалка по Tower Git это объясняется как: Сбросьте указатель HEAD на предыдущую фиксацию и сохраните незафиксированные локальные изменения — Петр

Когда я писал этот ответ, его не существовало . Во всяком случае git reset —keep более безопасная форма git reset —hard ; git reset —mixed вообще не трогает рабочий каталог. — Якуб Наребски

Возможно, вы случайно повредили файл .git / index с помощью sed в корне вашего проекта (возможно, рефакторинг?), Например:

чтобы избежать этого в будущем, просто игнорируйте двоичные файлы с помощью grep / sed:

ответ дан 19 мар ’11, в 07:03

Если вы не против потерять изменения в .git/index , вы всегда можете удалить его и создать заново с помощью git reset (без —hard !). — Якуб Наребски

Я сломал его с помощью # find ./ -type f -exec sed -i ‘s / Politician / Legislator / g’ <> ; Выполнение того, что рекомендует этот ответ, в первую очередь не сломало бы его, но принятый ответ устранил ущерб, который я нанес. Но это отличная профилактика. — Райан Мортенсен

@RyanMortensen Вы можете попробовать инвертировать sed с чем-то вроде find .git/ -type f -exec sed -i ‘s/Legislator/Politician/g’ <> ; Это может помочь, если ваш .git/ настолько испорчен, что git reset не сработает. Или, может быть, вы хотите восстановить существующие .git/index не удаляя его. Конечно, это не удастся, если в вашем исходном коде или указателе уже есть некоторые «законодатели». — варочные панели

Спасибо @hobs, вы избавили меня от многих проблем — я решил это инвертированием sed заменив мой new_string с моим old_string ! — цвети_ико

Я реорганизовал весь свой проект вместо папки src в IntelliJ и столкнулся с этой проблемой. Это объясняет, почему у меня были такие странные ошибки! — Майкл

У меня была эта проблема, и я пытаюсь ее исправить:

НО это не сработало. решение? По какой-то причине у меня были другие папки .git в подкаталогах. Я удаляю эти папки .git (не основные) и git reset очередной раз. Как только они были удалены, все снова заработало.

Создан 24 июля ’15, 14:07

Этот ответ действительно решает проблему, если у вас есть папки .git в vendor / (ex) — АльСан

Звучит как плохой клон. Вы можете попробовать следующее, чтобы получить (возможно?) Больше информации:

Создан 12 июля ’09, 12:07

Поскольку приведенные выше решения оставили у меня постоянные проблемы, я использовал это унылое решение:

  1. клонировать новую копию репо в другом месте
  2. скопируйте свежий каталог .git в (сломанный) репо, содержащий изменения, которые я хотел зафиксировать

Сделал свое дело. Кстати, я сделал sed в корне проекта, как догадался @hobs. Усвоил урок.

Это не очень хорошо, если вы были в середине слияния, создали ветки или выполнили какие-либо коммиты с момента клонирования, или любой из ряда других сценариев . Клонирование новой копии репо вряд ли является решением, и я осмелюсь предположить это попахивает нетерпением (лучше оставить в крайнем случае). Гораздо лучше действительно диагностировать, что происходит, и восстановить индекс существующего репо — обычно это относительно легко сделать. Иногда вы можете просто переименовать индексный файл (или удалить его, если вы уверены, что он вам больше не понадобится) и позволить Git создать новый (используя git-reset или git-checkout) .. — Джазимов

Это сработало для меня. Хотя мне любопытно, почему я вообще начал получать ошибки. Когда я вчера вышел из системы, все было нормально. Авторизоваться сегодня утром не было.

ответ дан 27 окт ’16, 09:10

Это сработало для меня, хотя он удалил все добавленные файлы из git. Мне пришлось запустить git add для этих файлов — Шамсул Арефин Саджиб

Примечание для пользователей подмодуля git — решения здесь не будут работать для вас как есть.

Допустим, у вас есть родительский репозиторий с именем dev , например, и ваш репозиторий подмодулей называется api .

если ты внутри api и вы получите ошибку, упомянутую в этом вопросе:

error: bad index file sha1 signature fatal: index file corrupt

Компания index файл НЕ будет внутри .git папка. Фактически, .git даже не будет папкой — это будет текстовый документ с местонахождением реальных данных .git для этого репозитория. Скорее всего что-то вроде этого:

/dev/api $ cat .git gitdir: ../.git/modules/api

Итак, вместо rm -f .git/index , вам нужно будет сделать это:

rm -f ../.git/modules/api/index git reset

или, в более общем плане,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index git reset

Источник

Error Description :

  • After git init, if we add and commit a few files, make some changes, add and committed. Set up the git daemon (running under Cygwin on WinXP) and clone the repository once, We get this error with the cloned repository:
$ git status
error: bad index file sha1 signature
fatal: index file corrupt
click below button to copy the code. By Git tutorial team
  • Is there any way to fix this, other than getting a new copy of the repository?

Solution 1:

  • If the problem is with the index as the staging area for commits (i.e. .git/index), we can simply remove the index (make a backup copy if we want), and then restore index to version in the last commit:
  • On OSX/Linux:
rm -f .git/index
git reset
click below button to copy the code. By Git tutorial team
  • On Windows:
del .gitindex
git reset
click below button to copy the code. By Git tutorial team
  • (The reset command above is the same as git reset --mixed HEAD)
  • We can alternatively use lower level plumbing git read-tree instead of git reset.
  • If the problem is with index for packfile you can recover it using git index-pack.

Solution 2:

  • We could try the following to get (possibly?) more information:
git fsck --full
click below button to copy the code. By Git tutorial team

Solution 3:

  • This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Solution 4:

  • Clone a new copy of the repo elsewhere
  • Copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Solution 5:

  • This might solve our problem.
rm .git/index

git reset
click below button to copy the code. By Git tutorial team

When submitting the file to the warehouse, the following error is thrown:

Report an error

[email protected] MINGW64 /e/note/Git (master)
$ git add git_GitHub.md
error: bad signature
fatal: index file corrupt

Cause Analysis

Because index file generally refers to the file .git/index in git. This file saves the information in the temporary storage area (index information). You can use git ls-files –stage to view the contents of the staging area. This file is very important! But now it reports index file corrupt, indicating that this file has been damaged. Fortunately, we have a way to regenerate this file: git read-tree or directly git reset.

Solution

  1. Enter the project directory: cd /path/to/dir
  2. Delete or rename the .git/index file: rm -f .git/index or mv .git/index{,.bak}
  3. Rebuild .git/index: git read-tree or directly git reset
[email protected] MINGW64 /e/note (master)
$ mv .git/index .git/index.bak

[email protected] MINGW64 /e/note (master)
$ git reset
Unstaged changes after reset:
M       Git/git_use.md
M       Git/git_para.md

[email protected] MINGW64 /e/note (master)
$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   "Git/git347232204345210235346254241344275277347224250.md"
        modified:   "Git/git347232204351200211351241271345217202346225260.md"

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        Git/git failed to push some refs to github.md
        "Git/git 346212245351224231 index file corrupt.md"
        "Git/git350277236346216245GitHub344273245345217212346216250351200201350207263344273223345272223.md"

no changes added to commit (use "git add" and/or "git commit -a")

Roc@DESKTOP-AF552U2 MINGW64 /e/note (master)

[Solved-5 Solutions] How to resolve “Error: bad index Fatal: index file corrupt” when using Git

Error Description :

  • After git init, if we add and commit a few files, make some changes, add and committed. Set up the git daemon (running under Cygwin on WinXP) and clone the repository once, We get this error with the cloned repository:
click below button to copy the code. By Git tutorial team
  • Is there any way to fix this, other than getting a new copy of the repository?

Solution 1:

  • If the problem is with the index as the staging area for commits (i.e. .git/index ), we can simply remove the index (make a backup copy if we want), and then restore index to version in the last commit:
  • On OSX/Linux:
click below button to copy the code. By Git tutorial team
click below button to copy the code. By Git tutorial team
  • (The reset command above is the same as git reset —mixed HEAD )
  • We can alternatively use lower level plumbing git read-tree instead of git reset.
  • If the problem is with index for packfile you can recover it using git index-pack .

Solution 2:

  • We could try the following to get (possibly?) more information:
click below button to copy the code. By Git tutorial team

Solution 3:

  • This issue can occur when there is a .git directory underneath one of the subdirectories. To fix it, check if there are other .git directories there, and remove them and try again.

Solution 4:

  • Clone a new copy of the repo elsewhere
  • Copy the fresh .git directory into the (broken) repo that contained the changes I wanted to commit

Solution 5:

click below button to copy the code. By Git tutorial team

Related Searches to How to resolve “Error: bad index – Fatal: index file corrupt” when using Git

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

Как решить проблему «Ошибка: неверный индекс — Неустранимый: файл индекса поврежден» при использовании Git

После git init , Я добавил и зафиксировал несколько файлов, внес некоторые изменения, добавил и зафиксировал. Настройте демон git (работающий под Cygwin на WinXP) и один раз клонируйте репозиторий. Теперь я получаю эту ошибку с клонированным репозиторием:

Есть ли способ исправить это, кроме получения новой копии репозитория?

задан 12 июля ’09, 08:07

Это в клонированном репозитории или в исходном репозитории? Выдала ли команда clone какие-либо ошибки? — CB Bailey

14 ответы

Если проблема связана с индексом как область подготовки коммитов (т.е. .git/index ), вы можете просто удалить индекс (сделать резервную копию, если хотите), а затем восстановить индекс до версии в последней фиксации:

( reset команда выше такая же, как git reset —mixed HEAD )

Вы также можете использовать более низкий уровень водопровод git read-tree вместо git reset .

Если проблема в индекс для пакетный файл, вы можете восстановить его, используя git index-pack .

Я случайно сделал :w! в :Gstatus (из fugitive.vim). Этот ответ избавил меня от необходимости тянуть за волосы. — Лоуренс Гонсалвес

Я знаю, что нам не нравятся сообщения «мне тоже» — но «мне тоже». Эквивалент в Windows erase /s .gitindex , Мне нужен был erase .gitindex.lock тоже. — Джереми МакГи

Привет, у меня была такая же проблема с поиском и заменой, но git reset сообщает мне, что в .git / objects / pack / есть два файла пакета, к которым нет доступа. У тебя есть идея? — эпсилоны

не было бы безопаснее использовать git reset —keep вместо? в Шпаргалка по Tower Git это объясняется как: Сбросьте указатель HEAD на предыдущую фиксацию и сохраните незафиксированные локальные изменения — Петр

Когда я писал этот ответ, его не существовало . Во всяком случае git reset —keep более безопасная форма git reset —hard ; git reset —mixed вообще не трогает рабочий каталог. — Якуб Наребски

Возможно, вы случайно повредили файл .git / index с помощью sed в корне вашего проекта (возможно, рефакторинг?), Например:

чтобы избежать этого в будущем, просто игнорируйте двоичные файлы с помощью grep / sed:

ответ дан 19 мар ’11, в 07:03

Если вы не против потерять изменения в .git/index , вы всегда можете удалить его и создать заново с помощью git reset (без —hard !). — Якуб Наребски

Я сломал его с помощью # find ./ -type f -exec sed -i ‘s / Politician / Legislator / g’ <> ; Выполнение того, что рекомендует этот ответ, в первую очередь не сломало бы его, но принятый ответ устранил ущерб, который я нанес. Но это отличная профилактика. — Райан Мортенсен

@RyanMortensen Вы можете попробовать инвертировать sed с чем-то вроде find .git/ -type f -exec sed -i ‘s/Legislator/Politician/g’ <> ; Это может помочь, если ваш .git/ настолько испорчен, что git reset не сработает. Или, может быть, вы хотите восстановить существующие .git/index не удаляя его. Конечно, это не удастся, если в вашем исходном коде или указателе уже есть некоторые «законодатели». — варочные панели

Спасибо @hobs, вы избавили меня от многих проблем — я решил это инвертированием sed заменив мой new_string с моим old_string ! — цвети_ико

Я реорганизовал весь свой проект вместо папки src в IntelliJ и столкнулся с этой проблемой. Это объясняет, почему у меня были такие странные ошибки! — Майкл

У меня была эта проблема, и я пытаюсь ее исправить:

НО это не сработало. решение? По какой-то причине у меня были другие папки .git в подкаталогах. Я удаляю эти папки .git (не основные) и git reset очередной раз. Как только они были удалены, все снова заработало.

Создан 24 июля ’15, 14:07

Этот ответ действительно решает проблему, если у вас есть папки .git в vendor / (ex) — АльСан

Звучит как плохой клон. Вы можете попробовать следующее, чтобы получить (возможно?) Больше информации:

Создан 12 июля ’09, 12:07

Поскольку приведенные выше решения оставили у меня постоянные проблемы, я использовал это унылое решение:

  1. клонировать новую копию репо в другом месте
  2. скопируйте свежий каталог .git в (сломанный) репо, содержащий изменения, которые я хотел зафиксировать

Сделал свое дело. Кстати, я сделал sed в корне проекта, как догадался @hobs. Усвоил урок.

Это не очень хорошо, если вы были в середине слияния, создали ветки или выполнили какие-либо коммиты с момента клонирования, или любой из ряда других сценариев . Клонирование новой копии репо вряд ли является решением, и я осмелюсь предположить это попахивает нетерпением (лучше оставить в крайнем случае). Гораздо лучше действительно диагностировать, что происходит, и восстановить индекс существующего репо — обычно это относительно легко сделать. Иногда вы можете просто переименовать индексный файл (или удалить его, если вы уверены, что он вам больше не понадобится) и позволить Git создать новый (используя git-reset или git-checkout) .. — Джазимов

Это сработало для меня. Хотя мне любопытно, почему я вообще начал получать ошибки. Когда я вчера вышел из системы, все было нормально. Авторизоваться сегодня утром не было.

ответ дан 27 окт ’16, 09:10

Это сработало для меня, хотя он удалил все добавленные файлы из git. Мне пришлось запустить git add для этих файлов — Шамсул Арефин Саджиб

Примечание для пользователей подмодуля git — решения здесь не будут работать для вас как есть.

Допустим, у вас есть родительский репозиторий с именем dev , например, и ваш репозиторий подмодулей называется api .

если ты внутри api и вы получите ошибку, упомянутую в этом вопросе:

error: bad index file sha1 signature fatal: index file corrupt

Компания index файл НЕ будет внутри .git папка. Фактически, .git даже не будет папкой — это будет текстовый документ с местонахождением реальных данных .git для этого репозитория. Скорее всего что-то вроде этого:

/dev/api $ cat .git gitdir: ../.git/modules/api

Итак, вместо rm -f .git/index , вам нужно будет сделать это:

rm -f ../.git/modules/api/index git reset

или, в более общем плане,

rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index git reset

Источник

git bad signature index file corrupt #648

Comments

giuse88 commented May 25, 2015

Often vim-fugitive corrupts my git index. This happens when I call Gstatus and then I add the same file more the one with — . Any one else has this problem?

The text was updated successfully, but these errors were encountered:

tpope commented May 25, 2015

Next time it happens take a look inside the index file and see if the contents of the :Gstatus window have overwritten it.

cj commented Jun 25, 2015

@giuse88 @tpope not sure if this is related, but on the latest version of vim-fugative after I wq to save a commit I get this error: and then this shows up .

If I use vim to check .git/index I see:
using nano I see:

tpope commented Jun 25, 2015

Sounds like an issue with whatever this «BufSurf» plugin is.

On Thu, Jun 25, 2015 at 10:54 AM cj notifications@github.com wrote:


Reply to this email directly or view it on GitHub
#648 (comment).

cj commented Jun 25, 2015

this is the plugin https://github.com/ton/vim-bufsurf. It only just started happening after I updated fugitive. I guess something changed that bufsurf doesn’t like.

tpope commented Jun 25, 2015

If you can figure out the exact commit that triggered it I can further advise.

mataps commented Aug 5, 2015

i’m having the same issue when doing Gcommit then I added a file to stage. After that, I did another Gcommit, this time with a the message and I got this error.

cj commented Nov 11, 2015

@tpope so I’m still having this issue. I no longer have that plugin, but after I commit I’m still getting this:

tpope commented Nov 11, 2015

cj commented Nov 11, 2015

After I do a :Gwrite then :Gcommit type in my message and then :wq this buffer just pops up.

tpope commented Nov 11, 2015

So the commit message buffer closes and then this opens in a split? That’s odd. It looks like a failed attempt to open :Gstatus , which is what happens when you call :Gcommit with no changes.

Can you check the value of :echo b:fugitive_commit_arguments before you :wq ?

cj commented Nov 11, 2015

Yes. Strange, there definitely was a commit with changes before I did :wq ‘d.

here’s the value: —cleanup=strip -F /home/cj/apps/acd/autolink/.git/COMMIT_EDITMSG —no-edit —no-interactive —no-signoff

tpope commented Nov 11, 2015

While the commit message is still open, try running the following in another window:

Check for errors, and the exit status ( echo $? ).

cj commented Nov 11, 2015

fourjay commented Mar 17, 2016

I’ve run into this (pretty consistently). I’ve tried the troubleshooting
steps without seeing much different than reported above. That said I
think I might have found a workaround (and thus a pointer) My (less then
full perusal) of the code shows that the commit window is normally set
with bufhidden=bdelete but on commit it’s set to bwipeout . It
looks like some path allows that to get skipped. After a commit I can
still see the hidden .git/index file with ls! If I switch to the file at
that point (either directly or by invoking Gstatus) I see the garbled
binary index.

To clarify a bit:

  1. I use Gtatus. Everything is good
  2. I commit a change with Gcommit
  3. At that point I can still see the .git/index file with ls!
  4. If switch to the window, it’s garbled
  5. If I close that window and re-invoke Gstatus, it’s back to expected.

If I bwipeout the buffer directly ( :[BNUMBER]bwipeout ) then
Gstatus and cousins work fine.

The workaround (and possible clue) is that I typically use ZZ as a wq
shortcut. In after/gitcommit.vim I’ve now set a function + mapping that
calls bwipeout and the problem goes away (aka I remap ZZ)

Hoping this is useful 🙂

yevhen-m commented Nov 4, 2016

@cj I have the same issue with garbled text after GCommit command. Have you managed to fix it somehow?

unChartedZone commented Nov 17, 2016

Is anyone here who is having this issue, using vim-airline by any chance?

yevhen-m commented Nov 17, 2016

unChartedZone commented Nov 17, 2016

@yevhen-m I noticed that the issue with fugitive goes away when I uninstall vim-airline, so perhaps that plugin could be the cause of the issue but I’m not entirely sure.

pedrofranceschi commented Nov 18, 2016

I’m having the same issue… Any fix available?

darkalia commented Nov 22, 2016 •

Hello, I can confirm that this is related to airline. I hit this after switching to Xenial (the exact same setup was working fine on 15.10).

Here is my .vimrc file

/.vim/bundle/Vundle.vim call vundle#begin() » alternatively, pass a path where Vundle should install plugins «call vundle#begin(‘

/some/path/here’) » let Vundle manage Vundle, required Plugin ‘gmarik/Vundle.vim’ » Add all your plugins here (note older versions of Vundle used Bundle instead » of Plugin)* » Auto-Complete Bundle ‘Valloric/YouCompleteMe’ » Folding Plugin ‘tmhedberg/SimpylFold’ «Folding » Python autodindent Plugin ‘vim-scripts/indentpython.vim’ » Indent python » Syntax Plugin ‘scrooloose/syntastic’ «Syntax checker » Plugin ‘nvie/vim-flake8’ » PEP8 » Colors Plugin ‘jnurmine/Zenburn’ » Zenburn theme (console) Plugin ‘altercation/vim-colors-solarized’ «Solarized theme (GUI) Plugin ‘scrooloose/nerdtree’ «Hierarchy tree Plugin ‘kien/ctrlp.vim’ » Search files Plugin ‘vim-airline/vim-airline’ «Status bar Plugin ‘vim-airline/vim-airline-themes’ Plugin ‘tpope/vim-fugitive’ » Show git branch in status bar Plugin ‘xolox/vim-misc’ » Needed by vim-session Plugin ‘xolox/vim-session’ » Make use of mksession easier Plugin ‘saltstack/salt-vim’ » For saltstack files Plugin ‘fatih/vim-go’ » Go Plugin Plugin ‘pearofducks/ansible-vim’ » Ansible plugin Bundle ‘Rykka/riv.vim’ » All of your Plugins must be added before the following line call vundle#end() » required filetype plugin indent on » required set encoding=utf-8 » Set filetype based on name autocmd BufRead,BufNewFile *Dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *dockerfile* setlocal filetype=dockerfile autocmd BufRead,BufNewFile *.spec.in setlocal filetype=spec autocmd BufRead,BufNewFile *.functions setlocal filetype=sh autocmd BufRead,BufNewFile *.sls setlocal filetype=sls autocmd BufRead,BufNewFile *.jinja setlocal filetype=jinja «» General section set nowrap » don’t wrap lines set tabstop=4 » a tab is four spaces set backspace=indent,eol,start » allow backspacing over everything in insert mode set autoindent » always set autoindenting on set copyindent » copy the previous indentation on autoindenting set shiftwidth=4 » number of spaces to use for autoindenting set shiftround » use multiple of shiftwidth when indenting with ‘ ‘ set showmatch » set show matching parenthesis set ignorecase » ignore case when searching set smartcase » ignore case if search pattern is all lowercase, » case-sensitive otherwise set smarttab » insert tabs on the start of a line according to » shiftwidth, not tabstop set hlsearch » highlight search terms set incsearch » show search matches as you type set history=1000 » remember more commands and search history set undolevels=1000 » use many muchos levels of undo set wildignore=*.swp,*.bak,*.pyc,*.class set visualbell » don’t beep set noerrorbells » don’t beep » FX button mapping set pastetoggle= » Toggle PASTE mode » Remove trailing whitespaces :nnoremap :let _s=@/ :%s/s+$//e :let @/=_s :nohl :unlet _s set hidden » Allow leaving a buffer with unsaved changes set mouse=a » Use mouse in all mode set guioptions-=T «remove toolbar » Completion in menu bar set wildmode=longest,list,full set wildmenu «» Remap » sv sources .vimrc nnoremap sv :source $MYVIMRC :runtime! plugin/settings/* :redraw :echo $MYVIMRC ‘reloaded’ » Buffer navigation nnoremap :bp nnoremap :bn » Split navigations nnoremap l nnoremap h nnoremap k nnoremap j » Copy to system clipboard Visual selection » vnoremap y/ «* «» Folding » Enable folding set foldmethod=indent set foldlevel=99 » See the docstring when folding let g:SimpylFold_docstring_preview=1 » Autocompletion stuff let g:ycm_autoclose_preview_window_after_completion=1 map g :YcmCompleter GoToDefinitionElseDeclaration » Colors set if has(‘gui_running’) set background=dark colorscheme solarized set guifont=DejaVu Sans Mono for Powerline 9 else «colors theme configuration (console) if &term == «linux» || &term == «screen.linux» set t_Co=8 colorscheme zenburn else set t_Co=256 colorscheme zenburn endif endif «» NerdTree let NERDTreeIgnore=[‘.pyc$’, ‘

$’] «ignore files in NERDTree map :NERDTreeToggle » Close vim if only NerdTree is open autocmd bufenter * if (winnr(«$») == 1 && exists(«b:NERDTree») && b:NERDTree.isTabTree()) | q | endif » Always enable status bar set laststatus=2 » Use powerline font symbols let g:airline_powerline_fonts = 1 if !exists(‘g:airline_symbols’) let g:airline_symbols = <> endif let g:airline_symbols.space = «ua0″ » Enable the list of buffers let g:airline#extensions#tabline#enabled = 1 » Session let g:session_autosave = «prompt» let g:session_autosaveperiodic = 60 let g:session_persist_colors = 0 let g:session_persist_font = 0″>

As long as I keep the vim-airline plugin, if I edit a file, :Gwrite, :Gcommit, I end up with a window with the .git/index content like this
DIRC�������CX/�� yada yada

The title of the window being «/.git/index» [Preview]
I can just close it but it’s rather annoying

As long as I remove vim-airline plugin, this does not happen anymore

Using previous version of vim-airline has lead nowhere so far, but still checking

Источник

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
August 5, 2022

Popularity
8/10

Helpfulness
9/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • git add . error: bad signature 0x00000000 fatal: index file corrupt
  • Related Problems

  • $ git status error: bad signature 0x00000000 fatal: index file corrupt
  • error: bad signature 0x00000000
  • bad signature 0x00000000
  • Couldn’t check the working tree for unmerged files because of an error. bad signature 0x00000000 index file corrupt
  • How to solve bad signature… index file corrupt
  • TPC Matrix View Full Screen

    git add . error: bad signature 0x00000000 fatal: index file corrupt

    Comment

    0


    Popularity

    8/10 Helpfulness
    9/10
    Language
    shell

    Source: Grepper

    Tags: corrupt
    file
    git-add
    shell
    signature

    Muiz Ather

    Contributed on Aug 05 2022

    Muiz Ather

    21 Answers  Avg Quality 5/10


    Понравилась статья? Поделить с друзьями:
  • Error arguments invalid visual
  • Error argument expected one argument
  • Error area 913 что это
  • Error bad return status for module build on kernel
  • Error archive structure corrupted descriptor failed crc check