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

妖精的绣舞 提交于 2019-12-19 21:52:57

问题


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?


回答1:


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



回答2:


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

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



回答3:


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.




回答4:


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"


来源:https://stackoverflow.com/questions/18008508/bash-how-to-check-if-packages-can-be-installed-if-apt-get-dpkg-is-running

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