git index.lock File exists when I try to commit, but cannot delete the file

When I do ‘git commit’, I’m getting the following:

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

  • Git make remote master point to another branch
  • rsync exclude according to .gitignore & .hgignore & svn:ignore like --filter=:C
  • What's the easiest way to merge all but one change from a branch in Git?
  • Git: Equivalent of repair move from SVN
  • Git commit bash script
  • Including specific file extension in gitignore
  • However, when I do ls project_path/.git/index.lock it’s saying the file doesn’t exist. Any thoughts on what I should do? I’ve also noticed that project_path/.git is owned by root, not sure if that has anything to do with the problem I’m encountering.

    git version is 1.7.5.4

    edit: 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.

  • Progress indicator for git clone
  • Git fetch failing using jgit: Remote does not have <branchname> available for fetch
  • GitHub: Using UTF-8 encoding for files
  • Closing tickets in Trac with Git commit message
  • How to retain commit gpg-signature after interactive rebase squashing?
  • Forking a repository on github
  • 25 Solutions collect form web for “git index.lock File exists when I try to commit, but cannot delete the file”

    This may be an old reply but I’m hoping this is more useful on next who need this solution.

    On linux/unix/gitbash/cygwin, try

    rm -f .git/index.lock

    On Windows Command Prompt, try:

    del .git\index.lock

    Hope that helps, I found this solution here: Fatal: Unable to create ‘…git/index.lock’ File exists

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

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

    1. Go to: Tools > Options > Source Control
    2. Select Current source control plug-in as: None

    For Windows:

    • From a powershell console opened as admin, try
    > rm -f ./.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 -f ./.git/index.lock
    
    1. check if the git still running (ps -ef | grep git)
    2. if not, remove the locked file
    3. if yes, kill the git process at first.

    Probably (it has happened to me), ls command is saying it doesn’t exist because 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

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

    so what you can do is manually delete index.lock file from your .git directory.

    rm -f ./.git/index.lock
    

    cd into you project directory and run this command.

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

    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.

    Unless you actually intended for root to own your repo, 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 repo 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.

    I had this problem with SourceTree when switching branch by double-click 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 branch you want to switch, just right click and choose “Checkout [branch name]”. It should succeed now.

    ok I have solved this problem.

    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 power shell or simply cmd. Now you can use git commands to continue)

    I also have this question in windows 10.

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

    I finally got the reason:

    the computer have two process to use git:

    • git bash
    • cmder

    so I use cmder.exe to git commit it will occur errors.

    so the solution is use git bash or Terminate the git bash then use cmder.exe

    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 repo into this repo, including the .git invisible folder. So, SourceTree was confused about which repo I wanted to stage files to (there being a mismatch between the repo SourceTree thought I was in, and the one that the contents of my embedded .git dir said I should be in).

    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 command prompt, it said the file was in use by another process.

    I found that I had 2 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.

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

    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.

    I created an empty index.lock file, deleted it using windows command

    In my sourceTree application i am not able to do commit or switch to any other commit/brach. That time shows error like

    fatal: Unable to create blah blah blah..

    I simply resolve this by goto .git folder(in project Explorer Dir). And delete the Index —– [file type: LOCK file].Now i get back all access in sourceTree..

    please make sure Index lock file.. suppose you dont get file type, change fileview settings in computer. Note: .git folder is normally hidden type of folder.

    In Windows I cannot get this working using the del (or rm) command. I just have no rights or when I’m superuser, the file is in use and cannot be removed. But this is what I do:

    • close all the cmd/cmder sessions (I get a warning that scripts are running although I have none).
    • open cmd/cmder with superuser permissions.
    • run the actual git add/commit commands as superuser.
    • now with my normal user, I push the changes. Now everything works fine again.

    Note that I don’t delete the index.lock anywhere. When I close the console, it goes away and if I try to do something with my normal user, it returns. Pretty annoying, but this procedure works every time.

    I have no clue to what’s happening, but this seems to occur when I do major changes to my projects, for example converting a project to maven/gradle source folder structure from something else. This results in a huge number of changes, only because files get moved up tremendously.

    EDIT: occasionally I need to do some special tricks:

    • open the task manager and kill git processes before being able to add/reset/commit.
    • go to the file/in/very/deep/folder/structure/location to do the operation.

    UPDATE:

    • using Cmder seems to cause a lot git process problems.

    Multiple git clients working on 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 MSVS 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 5 tries, 3 seconds between each. It never removes the index.lock, assuming user should intervene. It was extracted from a larger commit script. It only has minimal testing with simple arguments.

    • Copy script to C:\bin and add C:\bin to $PATH.
    • From PS1> gitr –help
    • From DOS %> 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
    }
    

    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.

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

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

    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.

    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 IDE open like Visual Studio or related software that git is integrated into. Close it and try re-stashing your file. Hope it helps.

    If you are using GIT BASH For Windows :-

    Run these two commands
    1. cd .git
    2. rm index.lock

    Git Baby is a git and github fan, let's start git clone.