There are many ways to find whether a package is installed or not in Ubuntu. For example if we want to find whether vim
is installed or not in Ubuntu we can use any of the following commands:
dpkg -s vim
dpkg --get-selections | grep 'vim' #I always prefer this one as it shows other packages that has the pattern `vim` in their names, very useful in some cases
dpkg -l vim
apt-cache policy vim
Now if want to install a package after finding that its not installed already, just do the following (here we are installing vim
, just replace vim with whatever package you want):
sudo apt-get update #It will update the local cache of repositories, not mandatory but recommended
sudo apt-get install vim
Here is a simple bash
script to check if a package is installed or not, if not then it will install the package. It will ask you to input the name of the package.
#!/bin/bash
echo "What's the name of the package you want to check?"
read package
check=$(dpkg -s $package 2>/dev/null | sed -n '2,3p' | grep -o 'installed')
if [[ "$check" == 'installed' ]]
then
echo -e "$package is already Installed\n\n"
else
echo -e "$package is Not installed\n\n"
sudo apt-get install $package
fi