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

*爱你&永不变心* 提交于 2019-12-01 20:52:40

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

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

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

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.

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"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!