user28464
user28464

Reputation: 183

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

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?

Upvotes: 7

Views: 11720

Answers (4)

diogovk
diogovk

Reputation: 2228

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.

Upvotes: 2

Guss
Guss

Reputation: 32315

You can simply check if apt-get or dpkg are running:

ps -C apt-get,dpkg >/dev/null && echo "installing software" || echo "all clear"

Upvotes: 2

Onlyjob
Onlyjob

Reputation: 5868

Checking lock files is insufficient and unreliable. Perhaps what you really want to do is to check whether dpkg database is locked. I do it using the following approach:

## check if DPKG database is locked
dpkg -i /dev/zero 2>/dev/null
if [ "$?" -eq 2 ]; then
    echo "E: dpkg database is locked."
fi

Hopefully there is a better way...
Besides I also do the following check as it might be unsafe to install if there are broken packages etc.:

apt-get check >/dev/null 2>&1
if [ "$?" -ne 0 ]; then
    echo "E: \`apt-get check\` failed, you may have broken packages. Aborting..."
fi

Upvotes: 2

Ryley
Ryley

Reputation: 21216

In Debian Wheezy (currently stable), those files always exist. Therefore I found using lsof /var/lib/dpkg/lock to be a more useful check. It returns 1 if nothing is using the lock, 0 if it is, so:

lsof /var/lib/dpkg/lock >/dev/null 2>&1
[ $? = 0 ] && echo "dpkg lock in use"

Upvotes: 2

Related Questions