Bash - how to check if packages can be installed, if apt-get/dpkg is running?

user28464 picture user28464 · Aug 2, 2013 · Viewed 7.1k times · Source

In a bash script I want to install a package. Before sanely doing so, I need to check if no other instance of apt-get or dpkg is already working. If that was the case, the apt-get would fail, because its already locked.

Is it sufficient to check if /var/lib/dpkg/lock and /var/lib/apt/lists/lock exists and if both don't exist, installing is safe?

Answer

diogovk picture diogovk · Sep 30, 2013

It depends how well you want to handle apt-get errors. For your needs checking /var/lib/dpkg/lock and /var/lib/apt/lists/lock is fine, but if you want to be extra cautious you could do a simulation and check the return code, like this:

if sudo apt-get --simulate install packageThatDoesntExist      
then echo "we're good"
else echo "oops, something happened"
fi

which will give for instance:

Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package packageThatDoesntExist
oops, something happened

Edit: --simulate will not check for locks, so you might want to do an additional check there. You might also want to remove sudo, if you want to check for sudo separately.