Check if a package is installed and then install it if it's not

I'm working on a Ubuntu system and currently this is what I'm doing:

if ! which command > /dev/null; then
   echo -e "Command not found! Install? (y/n) c"
   read
   if "$REPLY" = "y"; then
      sudo apt-get install command
   fi
fi

Is this what most people would do? Or is there a more elegant solution?


To check if packagename was installed, type:

dpkg -s <packagename>

You can also use dpkg-query that has a neater output for your purpose, and accepts wild cards, too.

dpkg-query -l <packagename>

To find what package owns the command , try:

dpkg -S `which <command>`

For further details, see article Find out if package is installed in Linux and dpkg cheat sheet.


To be a little more explicit, here's a bit of bash script that checks for a package and installs it if required. Of course, you can do other things upon finding that the package is missing, such as simply exiting with an error code.

PKG_OK=$(dpkg-query -W --showformat='${Status}n' the.package.name|grep "install ok installed")
echo Checking for somelib: $PKG_OK
if [ "" == "$PKG_OK" ]; then
  echo "No somelib. Setting up somelib."
  sudo apt-get --force-yes --yes install the.package.name
fi

If the script runs within a GUI (eg it is a Nautilus script), you'll probably want to replace the 'sudo' invocation with a 'gksudo' one.


This one-liner returns 1 (installed) or 0 (not installed) for the 'nano' package..

$(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed")

even if the package does not exist / is not available.

The example below installs the 'nano' package if it is not installed..

if [ $(dpkg-query -W -f='${Status}' nano 2>/dev/null | grep -c "ok installed") -eq 0 ];
then
  apt-get install nano;
fi
链接地址: http://www.djcxy.com/p/57054.html

上一篇: 如何检查命令是否存在于shell脚本中?

下一篇: 检查是否安装了软件包,如果不是,则安装它