I ran into the “E: Could not get lock /var/lib/dpkg/lock” error the other day while running an Ansible playbook on a client node running Linux. “E: Could not get lock /var/lib/dpkg/lock” is a frustrating issue to solve as there isn’t very good documentation out there about how to fix it up.
The key thing that you need to understand in order to solve this issue is that Linux prevents a file from being accessed by multiple processes, it locks that file from being accessed by another process. So, if you want the currently running process to have precedence, you just have to wait for the process to finish, however, sometimes a process may be unresponsive, in which case, it’s best to just kill it.
So, you need to follow two simple steps in order to release the lock on /var/lib/dpkg/lock: first, see what process is currently accessing the file and second, kill that process.
Step 1: Identify the Process Accessing the File
In order to see which process is accessing the file, you need to use the
lsof command. The
lsof command, also known as the list of open files command, will provide you with the PID, or process id that is currently accessing the file that you want to unlock. In order to JUST get a list of all of the process ids accessing a file, use the
-t option. Otherwise, you will see a chart which shows the COMMAND, PID, USER, FD, TYPE, DEVICE, SIZE/OFF, and NODE. We just want the PID in our case because that’s the process that we need to kill.
lsof -t /var/lib/dpkg/lock
In our case, this returns the number 5321. Make sure to save the process id (number) that is returned to you, as you need to use it in the next step.
Step 2: Kill the Process
In order to kill a process in Linux, you need to use the kill command and make sure the next argument after the command is the process id (in our case 5321, but it will likely be different in your case).
That’s all there is to it, you should no longer be shown the “E: Could not get lock /var/lib/dpkg/lock” error if you attempt to run another process.