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?
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.