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)
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.
I've found all solutions above can produce a false positive if a package is installed and then removed yet the installation package remains on the system.
To replicate:
Install package apt-get install curl
Remove package apt-get remove curl
Now test above answers.
The following command seems to solve this condition:
dpkg-query -W -f='${Status}\n' curl | head -n1 | awk '{print $3;}' | grep -q '^installed$'
This will result in a definitive installed or not-installed
For Ubuntu, apt provides a fairly decent way to do this. Below is an example for google chrome:
apt -qq list google-chrome-stable 2>/dev/null | grep -qE "(installed|upgradeable)" || apt-get install google-chrome-stable
I'm redirecting error output to null because apt warns against using its "unstable cli". I suspect list package is stable so I think it's ok to throw this warning away. The -qq makes apt super quiet.
In Bash:
PKG="emacs"
dpkg-query -l $PKG > /dev/null || sudo apt install $PKG
Note that you can have a string with several packages in PKG.
I use the following way:
which mySQL 2>&1|tee 1> /dev/null
if [[ "$?" == 0 ]]; then
echo -e "\e[42m MySQL already installed. Moving on...\e[0m"
else
sudo apt-get install -y mysql-server
if [[ "$?" == 0 ]]; then
echo -e "\e[42mMy SQL installed\e[0m"
else
echo -e "\e[42Installation failed\e[0m"
fi
fi
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.
REQUIRED_PKG="some-package"
PKG_OK=$(dpkg-query -W --showformat='${Status}\n' $REQUIRED_PKG|grep "install ok installed")
echo Checking for $REQUIRED_PKG: $PKG_OK
if [ "" = "$PKG_OK" ]; then
echo "No $REQUIRED_PKG. Setting up $REQUIRED_PKG."
sudo apt-get --yes install $REQUIRED_PKG
fi
If the script runs within a GUI (e.g. it is a Nautilus script), you'll probably want to replace the 'sudo' invocation with a 'gksudo' one.