Check if an apt-get package is installed and then install it if it's not on Linux

John Jiang picture John Jiang · Aug 19, 2009 · Viewed 239.2k times · Source

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?

Answer

viam0Zah picture viam0Zah · Aug 19, 2009

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.