267

When I do 'git commit', I'm getting the following:

fatal: Unable to create 'project_path/.git/index.lock': File exists.

However, when I do ls project_path/.git/index.lock it's saying the file doesn't exist. What should I do? I've also noticed that project_path/.git is owned by root and am not sure if that has anything to do with the problem I'm encountering.

The Git version is 1.7.5.4


It seems that the problem most likely was another process I had running, that was writing (unbeknownst to me) to the project directory. I restarted my machine and then I had no problem committing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
asahi
  • 2,991
  • 2
  • 16
  • 17
  • 3
    It could very well be a permissions problem where Git assumes that since it can't create the file it already exists. Have you tried taking ownership of the directory or executing your command using sudo? –  Feb 14 '12 at 19:10
  • I got same error then I tried squash and reword in one rebase operation. I just del reword and all works fine, and reword on next rebase. – Denis Oct 18 '12 at 13:07
  • 1
    I think your explanation on another app accessing the git repo is correct. Had the same problem during a rebase. Gitx was running. Once I quit it git worked fine. – The Who Mar 12 '13 at 14:58
  • It works for me http://stackoverflow.com/questions/17916339/error-in-deleting-addind-file-from-appharbor-using-git-unable-to-create-f-git – Shailesh Jul 29 '13 at 05:42
  • 2
    @asahi: Do you maybe want to accept an answer? This will help future readers. – MERose Aug 03 '15 at 14:31
  • @MERose: I would, but this was 3 years ago on a different machine from the one I have now, and as can be seen by my updated post, I had figured out a solution. Not sure what can be done to help future readers, but I'm open to suggestions. – asahi Aug 03 '15 at 18:16
  • 2
    Possible duplicate of [Git - fatal: Unable to create '/path/my\_project/.git/index.lock': File exists.](http://stackoverflow.com/questions/7860751/git-fatal-unable-to-create-path-my-project-git-index-lock-file-exists) – Kristján Dec 04 '15 at 15:56
  • 3
    @asahi: You can post the content of your edit (which was the solution) as an answer and then accept that. (Although the more general solution than 'restart the machine' is that another process was accessing the directory; restarting just cuts through the Gordian knot of trying to figure out which one and why. : ) In my case, it was my IDE.) Anyway, people frequently answer their own questions when they find their own solutions, which you did. – Wilson F Jan 13 '16 at 19:49
  • Make sure to use git 2.8.4+ (June 2016). [See my answer below](http://stackoverflow.com/a/37710754/6309) – VonC Jun 08 '16 at 18:59
  • It seemed that killing my BabelJS compiler/watcher in the repo fixed the issue for me. I got the clue from @TheWho – allieferr Mar 27 '18 at 22:37

42 Answers42

444

On Linux, Unix, Git Bash, or Cygwin, try:

rm -f .git/index.lock

On Windows Command Prompt, try:

del .git\index.lock

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ryan S
  • 6,076
  • 1
  • 20
  • 14
  • 1
    I see that sometimes the lock file gets deleted automatically. Any clue why this file need to be deleted manually sometimes ? – Nrj Jan 06 '15 at 10:28
  • I don't have an index.lock, what do? :( – Alex C May 14 '15 at 17:56
  • 86
    Given that the problem in the question was that he was not able to delete the file, why do you think trying to delete the file should be the solution? – skyking Mar 11 '16 at 06:46
  • 4
    For me closing and opening SourceTree resolved the issue... Temporarily I suppose. – Andrew Aug 04 '16 at 13:34
  • Closing PHPStorm was also required this time. Maybe something in there is locking it. – Andrew Sep 02 '16 at 13:51
  • On Windows close all applications that use git then open the Task Manager and kill all git processes. Then delete the index.lock file. – John Meyer Jan 26 '17 at 18:48
  • 3
    @skyking in the original question there's an error that says `fatal: Unable to create 'project_path/.git/index.lock': File exists.`, it says "File exists", and deleting it would simple solution. Why would I suggest deleting a file if it's not even in the original question? – Ryan S Nov 08 '18 at 14:35
  • Windows: cd .git touch index.lock rm index.lock – Bang Andre Oct 26 '21 at 14:51
49

For Windows:

  • From a PowerShell console opened as administrator, try

    rm -Force ./.git/index.lock
    
  • If that does not work, you must kill all git.exe processes

    taskkill /F /IM git.exe
    

    SUCCESS: The process "git.exe" with PID 20448 has been terminated.
    SUCCESS: The process "git.exe" with PID 11312 has been terminated.
    SUCCESS: The process "git.exe" with PID 23868 has been terminated.
    SUCCESS: The process "git.exe" with PID 27496 has been terminated.
    SUCCESS: The process "git.exe" with PID 33480 has been terminated.
    SUCCESS: The process "git.exe" with PID 28036 has been terminated. \

    rm -Force ./.git/index.lock
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andrei Epure
  • 1,746
  • 1
  • 21
  • 30
21

On a Windows platform running Visual Studio 2015 RC (v4.6.00057) in combination with Sourcetree (v1.6.14.0), it will give this error as well.

Solution: Assuming you want to use Sourcetree as source code manager, simply disable the source control provider inside Visual Studio like this:

  1. Go to: menu ToolsOptionsSource Control
  2. Select Current source control plug-in as: None
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
WLCyPHlSpC
  • 339
  • 3
  • 3
14

Try

rm -f ./.git/index.lock

if you have no other Git process running, and then just delete the index.lock file of the respective project.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Touseef Murtaza
  • 1,548
  • 14
  • 20
  • 1
    Worked on my mac's environment. – AdamHurwitz Nov 20 '18 at 20:45
  • What context? [Linux](https://en.wikipedia.org/wiki/Linux)? (it [isn't Windows/PowerShell](https://pvm-professionalengineering.blogspot.com/2019/10/powershell-aliases-and-missing.html) as [Remove-Item](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-item) (the alias for `rm`) doesn't have option '`-f`'). – Peter Mortensen Mar 15 '23 at 09:55
  • @PeterMortensen yes correct in the context of Linux – Touseef Murtaza Mar 15 '23 at 12:04
13
  1. check if the Git process still running (ps -ef | grep git)
  2. if not, remove the locked file
  3. if yes, kill the Git process at first.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96
8

This is happening when you cancel pulling from origin in the middle.

So you can manually delete the index.lock file from your .git directory:

rm -f ./.git/index.lock

cd into your project directory and run this command.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rahul Vivek
  • 196
  • 1
  • 3
  • 9
    Given that the problem in the question was that he was not able to delete the file, why do you think trying to delete the file should be the solution? – skyking Mar 11 '16 at 06:45
  • +1 @skyking. Deleting a file is obvious, the problem is there is no file to delete and the problem persists. – Catsunami Mar 09 '18 at 20:36
8
  1. Close every window that is potentially affecting this .git/index.lock file
  2. Delete the .git/index.lock file.
  3. Open your command line editor and cd to the location of your Git files.

(If the file is created, simply from cd into that location, then the problem is your editor. Close your editor. Do not use this editor again for this task. Open a different kind of editor - Windows PowerShell or simply cmd. Now you can use Git commands to continue.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
7

I just had this issue... Gitbox was at fault. So maybe you had a GUI running that was causing problems.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MyztikJenz
  • 1,650
  • 14
  • 19
6

del .git\index.lock worked for me.

I was facing this issue while checking out a new branch from the master branch.

Check out easily happened after deleting the index.lock file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

Probably (it has happened to me), the ls command is saying it doesn't exist, because the current user doesn't have permissions to reach that directory or file.

Remove the lock and make sure you are executing Git with the right user in order to avoid permission problems.

If you are in a GNU/Linux box with sudo command:

sudo rm project_path/.git/index.lock
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
caligari
  • 2,110
  • 20
  • 25
  • In Windows, you can check to see if the folder is read-only with right-click->Properties->Attributes. – Matt Jan 26 '16 at 22:25
  • Given that the problem in the question was that the file was non-existing, why do you think trying to delete the file should be the solution? – skyking Mar 11 '16 at 06:47
  • @skyking Permission problems show the same error. Indeed, I came to this question because the title. I wrote my answer as one possible solution and some votes confirm that it occurs to other people too ;) – caligari Mar 12 '16 at 09:36
  • @caligari Not exactly. Permission problem gives another answer to `ls project_path/.git/index.lock`. – skyking Mar 14 '16 at 11:00
5

In my case simply, go to project_path/.git and delete the index.lock file. Try to push your code it will work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
satya prakash
  • 87
  • 1
  • 5
  • 1
    Orphaned index.lock file. Generally, if you have an index.lock file, it's because a Git process is running or waiting on a prompt for user input. However, if the editing process is terminated or becomes unresponsive, the index.lock file can be left behind and remain present even if no Git process is running. This orphaned index.lock file will prevent other Git processes from editing the repository. – Su Llewellyn Aug 24 '21 at 15:17
  • Removing an Orphaned index.lock file. Note on Windows it's just "index" with no lock extension. If you suspect that you have an orphaned index.lock file, first verify that you don't have any Git processes running. To check for long-running Git operations, open Task Manager, sort by name, and look for git.exe or other Git-related processes. If you see any, you can wait a few moments for them to complete and try the Git operation again. If you don't have any Git processes running, you can delete the index.lock file and try the Git operation again. – Su Llewellyn Aug 24 '21 at 15:17
  • The above comments are courtesy of the Git documentation on learn.microsoft.com. – Su Llewellyn Aug 24 '21 at 15:19
4

Sometimes Git creates a lock file associated with your repo while you are making any changes or most probably when you are using sub modules.

The error message will show you the path of the lock file.

Fix: Just manually go to the path in terminal and delete the lock file by

rm index.lock

It should help.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Suhail Bhat
  • 443
  • 4
  • 13
4

I had this problem with Sourcetree when switching branch by double-clicking on it. The problem is not very common and Atlassian knows about it, but they decided not to fix it.

Fortunately, there is a solution. Instead of double-clicking on a branch you want to switch, just right click and choose "Checkout [branch name]". It should succeed now.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark
  • 1,357
  • 16
  • 30
  • thanks, right click > checkout works as an alternative. the error message is quite misleading especially when index.lock does not exist. – Ernest Sep 30 '16 at 21:31
4

I have come across the very same scenario. I even haven't done any changes in my local code. I have just edited a file and reverted it. I have simply deleted the below file in the hidden .git folder. It worked!

project_path/.git/index.lock

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Don D
  • 726
  • 1
  • 9
  • 19
3

I ran into this problem today where Sourcetree had spawned several Git processes that kept running even after closing Sourcetree. Here is how I fixed it.

  1. Press Ctrl + Alt + Esc or type "Task Manager" in windows start to start Task Manager.
  2. Look for all processes named "git", "git-lfs", etc. as shown in the screenshot below. Right click and select "End process" to kill each of them.
  3. Delete the .git/index.lock file.

Screenshot of Task Manager, including some Git processes

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mbonness
  • 1,612
  • 1
  • 18
  • 20
3

Unless you actually intended for root to own your repository, this sounds like you accidentally ran a Git command as root (maybe even the initial clone/init). If you meant to do that, then you'll have to live with running all Git commands in the repository as root. If you didn't, run sudo chown your-user[:your-group] -R .git to take ownership of it, and then see if things work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cascabel
  • 479,068
  • 72
  • 370
  • 318
  • In my case I had messed up the mode of files and directories inside `.git` and I corrected them with: `find .git -type f -exec chmod 644 {} \;` and also `find .git -type d -exec chmod 755 {} \;` I had messed up the modes when moving my git project from one computer to the other – Megidd Apr 16 '17 at 14:23
  • 1
    In my case I added write permission to .git files `sudo chmod g+w .git -R` – Beatriz Fonseca Oct 31 '17 at 17:53
2

Starting git 2.8.4 (June 2016), this should not happen anymore.

See issue 755 which should also alleviate the issue (commit 2db0641):

Make sure temporary file handles are not inherited by child processes

Prevent child processes from inheriting a handle to index.lock.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
2

I also have this question in Windows 10.

when I tried del ./.git/index.lock, it told me cannot remove 'index.lock': Device or resource busy.

I finally got the reason:

The computer has two processes which uses Git:

I used cmder.exe to do git commit and errors occurred.

So the solution is use Git Bash or terminate Git Bash and then use cmder.exe.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ihewro
  • 21
  • 3
2

Multiple Git clients working on the same local repository compete for that lock. Each client should wait until the lock is released by the other party to be a good citizen. For us, Sourcetree or Visual Studio appear to be be doing some maintenance in the background while we were are running large commit scripts.

Perhaps 'git' itself should support a '--retriesWhenLocked 5' argument to support retries. or even default to this when run manually.

Here is a PowerShell wrapper around Git named "gitr" that retries until index.lock disappears, using default five tries, three seconds between each. It never removes the index.lock, assuming the user should intervene. It was extracted from a larger commit script. It only has minimal testing with simple arguments.

  • Copy the script to C:\bin and add C:\bin to $PATH.
  • From PowerShell: gitr --help
  • From DOS (cmd.exe): powershell gitr --help

gitr.ps1

    #requires -version 2
    <#
    .SYNOPSIS
        gitr
    .DESCRIPTION
        Run "git" as an external process with retry and capturing stdout stderr.
    .NOTES
      2017/05/16 crokusek: Initial version
    #>

    #---------------------------------------------------------[Initializations]--------------------------------------------------------

    #Set Error Action
    $ErrorActionPreference = "Stop";

    #----------------------------------------------------------[Declarations]----------------------------------------------------------

    $scriptDir = Split-Path $script:MyInvocation.MyCommand.Path
    #Set-Location $scriptDir

    ## Disabled logging
    # Log File
    # $logFile = "$($scriptDir)\getr.log"
    # If (Test-Path $logFile) { Clear-Content $logFile }

    #-----------------------------------------------------------[Functions]------------------------------------------------------------

    Function Log([string]$msg, [bool]$echo = $true)
    {
        $timestamp = "$(get-date -Format 'yyyy/MM/dd HH:mm:ss'):  "
        $fullmsg = $msg -replace '(?ms)^', $timestamp  # the (?ms) enables multiline mode

        ## Disabled Logging
        # Add-content $LogFile -value $fullmsg

        if ($echo)
        {
            Write-Host $msg
        }
    }

    Function ExecSimple([string]$command, [bool]$echo=$true, [bool]$stopOnNonZeroExitCode=$true)
    {
        $command, $args = $command -split " "
        return Exec $command $args $echo $stopOnNonZeroExitCode
    }

    Function Exec([string]$exe, [string[]]$arguments, [bool]$echo=$true, [bool]$stopOnNonZeroExitCode=$true)
    {
        # Passing $args (list) as a single parameter is the most flexible, it supports spaces and double quotes

        $orgErrorActionPreference = $ErrorActionPreference
        Try
        {
            $error.clear()  # this apparently catches all the stderr pipe lines

            if ($false -and $exe -eq 'git')  # todo make this a generic flag
            {
                $exe = "$($exe) 2>&1"
            }

            $output = ""

            $argflattened = $arguments -join ' '
            Log "`n% $($exe) $($arguments)`n"

            # This way some advantages over Invoke-Expressions or Start-Process for some cases:
            #      - merges stdout/stderr line by line properly,
            #      - echoes the output live as it is streamed to the current window,
            #      - waits for completion
            #      - works when calling both console and windows executables.
            #
            $ErrorActionPreference = "Continue"  # required in order to catch more than 1 stderr line in the exception

            if ($echo)
            {
                # Using "cmd.exe" allows the stderr -> stdout redirection to work properly.  Otherwise the 2>&1 runs after PS for
                # some reason.  When a command such as "git" writes to stderr, powershell was terminating on the first stderr
                # line (and stops capturing additional lines).
                #
                # but unfortuantely cmd has some bizarre de-quoting rules that weren't working for all cases.
                #& cmd /c "`"" $exe $arguments "`"" | Tee-Object -variable output | Write-Host | out-null

                # This is simplest but has some issues with stderr/stdout (stderr caught as exception below)
                #
                & $exe $arguments 2>&1 | tee -variable output | Write-Host | out-null
            }
            else
            {
                & $exe $arguments 2>&1 | tee -variable output | out-null
            }

            $output = $output -join "`r`n"

            if ($stopOnNonZeroExitCode -and !$LASTEXITCODE -eq 0)
            {
                throw [System.Exception] "Exit code ($($LASTEXITCODE)) was non-zero. Output:`n$($output)"
            }
        }
        catch [System.Management.Automation.RemoteException]
        {
            $output = $_.Exception.ToString().Replace("System.Management.Automation.RemoteException:", "").Trim()

            if ($output.Contains("fatal"))
            {
                throw
            }

            if ($echo)
            {
                Log $output
            }
        }
        finally
        {
            $ErrorActionPreference = $orgErrorActionPreference;
        }

        if (-not $output -eq "")
        {
            Log $output $false  # don't echo to screen as the pipe above did
        }

        return $output
    }

    Function ExecWithRetry([string]$exe, [string[]]$arguments, [bool]$echo=$true, [bool]$stopOnNonZeroExitCode=$true,
                          [int]$maxRetries = 5, [int]$msDelay = 3000, [AllowNull()][string]$exceptionMustContain = $null)
    {
        for ($i = 0; $i -lt $maxRetries; $i++)
        {
            try
            {
                Exec $exe $arguments $echo $stopOnNonZeroExitCode
                return
            }
            catch
            {
                if (-not [string]::IsNullOrEmpty($exceptionMustContain) -and $_.Exception.ToString().Contains($exceptionMustContain))
                {
                    Log "Last Error from $($exe) is retryable ($($i + 1) of $($maxRetries))" $true
                    Start-Sleep -Milliseconds ($msDelay);
                    continue
                }

                throw
            }
        }

        throw [System.Exception] "Unable to successfully exec '$($exe)' within $($maxRetries) attempts."
    }

    Function GitWithRetry([string[]]$arguments, [bool]$echo=$true)
    {
        ExecWithRetry "git" $arguments $echo -exceptionMustContain "Another git process seems to be running"
    }

#-----------------------------------------------------------[Main]------------------------------------------------------------

function Main([string[]]$arguments)
{
    GitWithRetry @($arguments)
}


#-------------------------------------- Startup ------------------------------------
try
{
    Main $args
    Exit 0
}
catch
{
    #Log "*** A fatal error occured: $($_.Exception)"
    #Read-Host -Prompt "`nA fatal error occurred, press enter to close."
    exit 1
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
crokusek
  • 5,345
  • 3
  • 43
  • 61
2

First you have to navigate to the specific folder of your project... Like if your project name is Firstproject, then first go to the directory of the project...

Then type cd .git.

Then after navigating to the Git folder, type del index.lock. After the deletion of the file index.lock, you will be able to commit and push as before.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

Is your code in a directory that Dropbox is syncing? Try pausing Dropbox.

I kept getting the same condition, but once I paused Dropbox (the interface gives you the option to pause for 30 minutes, 1 hour, ...), it never happened again.

Harry Pehkonen
  • 3,038
  • 2
  • 17
  • 19
1

I had this exact same error, but the issue was not the lock file. Instead the issue was that I had copied the contents of another Git repository into this repository, including the .git invisible folder.

So, Sourcetree was confused about which repository I wanted to stage files to (there being a mismatch between the repository Sourcetree thought I was in, and the one that the contents of my embedded .git directory said I should be in).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dmohr
  • 2,699
  • 1
  • 22
  • 22
1

I had this problem with TortoiseGit with Cygwin on Windows. I wasn't able to delete remove ./.git/index.lock even with administrative privileges. I tried both Cygwin and a command prompt, but it said the file was in use by another process.

I found that I had two instances of TortoiseProc.exe running. I killed one of them, and closed all of my Windows Explorer windows, and then was able to delete the file. I don't know if killing an instance of TortoiseProc.exe was the solution or closing Windows Explorer windows.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samuel
  • 8,063
  • 8
  • 45
  • 41
1

The solution for me was to delete the .index file and allow Git to rebuild another.

CAR182
  • 11
  • 1
1

I didn't have an inex.lock file to delete, but what worked for me was removing the Read-Only check from the Attributes window of the folder Properties dialog.

user3071434
  • 133
  • 1
  • 2
  • 13
1

I created an empty index.lock file, and deleted it using a Windows command.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

In my Sourcetree application I am not able to do a commit or switch to any other commit/branch. That time it shows an error like

fatal: Unable to create blah blah blah..

I simply resolve this by going to the .git folder (in the project explorer directory). And delete the index—[file type: LOCK file]. Now I get back all access in Sourcetree...

Please make sure the index lock file... Suppose you don’t get the file type, change the fileview settings on the computer. Note: the .git folder is normally a hidden type of folder.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

What did it for me was:

git rebase --abort and restart the rebase.

As Andrew mentioned, I was also using PhpStorm when this happened. I didn't have to close it, though.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Geert
  • 116
  • 3
1

In my case there wasn't any index.lock file to delete. I was trying to commit 109 files after formatting with Prettier. Committing less files at the time is what finally "resolved" the issue.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

In my case, it was Windows, not shut down completely.

Windows is hibernated, refused to mount.

Chances are that Windows really is hibernated. Windows does this automatically when you tell it to shutdown normally. The benefit is that you get a faster apparent start-up time.

To shutdown Windows without hibernating, issue the following at a command-prompt (in Windows):

shutdown /s

You might also want include /t 0 for immediate shutdown.

I found a nice tutorial to set up a launcher for this: How to Do a Full Shutdown in Windows 8 Without Disabling Hybrid Boot.

The simpler approach to actually shutting down Windows is to 'restart' (rather than 'shutdown'), but then intercept the boot process and boot Linux instead of letting it boot Windows.

Credit: nobar

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mukundhan
  • 3,284
  • 23
  • 36
1

This can also happen if you're using an alternate command line Git client, like hub.

I've been using hub as an aliased replacement for Git for a couple of years, but recently wrote a Bash script that does a bunch of Git work in it, and started to get this index lock issue.

I couldn't find the fix until I remembered I was running hub instead of Git. I removed that and the problem went away!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
1

This maybe because when you try to pull code and stop the process suddenly.

Just simple way to do:

  • rm -f ./.git/index.lock
  • after that, git status on the master/main branch
  • still see a lot of red color files. Run git reset --hard origin/master to remove all local changes and make it similar to origin/master.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hoang Subin
  • 6,610
  • 6
  • 37
  • 56
0

I am getting the error:

Using index info to reconstruct a base tree...
Falling back to patching base and 3-way merge...
fatal: Unable to create '/home/user/project/.git/index.lock': File exists.

If no other git process is currently running, this probably means a git process crashed in this repository earlier. Make sure no other git process is running and remove the file manually to continue.

But I couldn't find (nor delete) that .git/index.lock file.

In my case, Git Cola was running!

It obviously creates that .git/index.lock every once in a while, or caused by the rebase I was doing on the command line and during which I received that error - so Git Cola obviously "disturbs" the command line run of Git (or some Git CLI operations).

This is solved by closing git-cola during a command line git rebase.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cslotty
  • 1,696
  • 20
  • 28
0

Sometimes another Git client may interfere when there are multiple installed.

I.e., make sure with the Task Manager or Get-Process that TGitCache from TortoiseGit is not active in the background.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MovGP0
  • 7,267
  • 3
  • 49
  • 42
0

I had the same issue recently. If you will check the whole error message, it also says that there are some process that are using the Git process that blocks you from deleting index.lock.

You may have an IDE open, like Visual Studio, or related software that Git is integrated into. Close it and try re-stashing your file.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Borj
  • 43
  • 7
0

In Task Manager:

  1. develop all processes
  2. Kill all Git processes
  3. Delete the locked file
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0
  • The problem was solved for me by deleting the repository you are trying to commit the changes and clone the latest version from the remote (if using a remote Git server).
  • If it's local copy the data from directory and initialize a new Git repository.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Patrick Prakash
  • 500
  • 1
  • 7
  • 17
0

For me, the culprit was Windows security. It was blocking git.exe from running. You can check the notifications tab on the bottom right of your screen.

The message will show like this:

Virus and threat protection
unauthorized changes blocked
controlled folder access blocked git.exe from running
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ayush Kumar
  • 494
  • 1
  • 6
  • 21
0

If you are using Visual Studio (such as Visual Studio 2019) you can see this error occur when trying to commit changes with Git.

It can happen when you don't have a connection with Team Server. To correct it,

  1. Inside Visual Studio, from the Team menu, select the command Manage Connections.
  2. Look in the Solution Explorer -- you should see Team Explorer - Connect.
  3. Connect to the project you are working on by clicking it in the tree listed. (This step works if you have previously worked on the project.)
  4. Once connected, try your commit again.
Su Llewellyn
  • 2,660
  • 2
  • 19
  • 33
0

I did:

  1. removed the project.git\index file manually
  2. in the terminal: git reset
  3. synup project
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amal
  • 261
  • 4
  • 9
0

In my case I randomly get a

fatal: Не удалось создать «/home/mingun/project/.git/index.lock»: Файл существует.

Похоже, что другой процесс git запущен в этом репозитории,
например редактор открыт из «git commit». Пожалуйста, убедитесь,
что все процессы были завершены и потом попробуйте снова.
Если это не поможет, то возможно процесс git был ранее завершен
с ошибкой в этом репозитории:
удалите файл вручную для продолжени

message when I do a rebase, and I am quite sure that there aren't any other Git processes. At least a do not see any of them when I check them just after failing rebase command. Of course, every time I've immediately checked and saw that /home/mingun/project/.git/index.lock file did not exist.

Very often, I constantly get this error each time when I try to make a rebase, after few rebased commits the process failed with that error. To make matters worse, in most cases it is not possible to continue rebase:

git status

Output:

интерактивное перемещение в процессе; над e55e03330e3
Last commands done (21 commands done):
   pick 1a39bd4740d <skipped>
   pick f1906baf94b <skipped>
  (смотрите дополнительно в файле .git/rebase-merge/done)
Next commands to do (13 remaining commands):
   pick 98db21878ed <skipped>
   pick 30488ef5a5a <skipped>
  (используйте «git rebase --edit-todo», чтобы просмотреть или изменить их)
Вы сейчас перемещаете ветку «master» над «e55e03330e3».
  (все конфликты разрешены: запустите «git rebase --continue»)

Изменения, которые будут включены в коммит:
    новый файл:    <skipped>
    изменено:      <skipped>
git rebase --continue

Output:

fatal: не удалось прочитать файл журнала «.git/rebase-merge/message»: Нет такого файла или каталога
error: не удалось закоммитить проиндексированные изменения.

Sometimes, if I wait several seconds between attempts, git rebase (git svn rebase actually) command finishes with success. But often you have to wait and try 10 times or more. The longer rebase todo, the higher chance that it finishes with that error.

When I tried to reproduce this bug with an English messages to post results in the bugtracker I was surprised to discover, that using LANG=C always fixes the problem! I think it's very suspicious to be an accident.

Another reason why I think this is a Git bug is that these errors have only begun to occur recently (probably a year ago), although my Git work pattern has not changed for a while.

So, if you encounter the same problem as me, try to prepend LANG=C to your commands:

LANG=C git svn rebase
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mingun
  • 139
  • 1
  • 7
-2

If you are using Git Bash for Windows:

Run these two commands

  1. cd .git
  2. rm index.lock
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    Given that the problem in the question was that he was not able to delete the file, why do you think trying to delete the file should be the solution? – skyking Mar 11 '16 at 06:45