Script to check if some program is already installed

you can do this:

dpkg -s <packagename> &> /dev/null

then check exit status.only if the exit status of the above command was equal to 0 then the package installed.

so:

   #!/bin/bash

    echo "enter your package name"
    read name

    dpkg -s $name &> /dev/null  

    if [ $? -ne 0 ]

        then
            echo "not installed"  
            sudo apt-get update
            sudo apt-get install $name

        else
            echo    "installed"
    fi

Here's a function I wrote for the purpose that I use in my scripts. It checks to see if the required package is installed and if not, prompts the user to install it. It requires a package name as a parameter. If you don't know the name of the package a required program belongs to you can look it up. Information on that available here.

function getreq {
dpkg-query --show  "$1"
if [ "$?" = "0" ];
then
    echo "$1" found
else
    echo "$1" not found. Please approve installation.
    sudo apt-get install "$1"
    if [ "$?" = "0" ];
    then echo "$1" installed successfully.
    fi
fi
}

This line of command will check using the which program and will return 0 if installed and 1 if not:

which apache | grep -o apache > /dev/null &&  echo 0 || echo 1

Of course you will use it in this manner in your script:

which "$1" | grep -o "$1" > /dev/null &&  echo "Installed!" || echo "Not Installed!"

A simple usage would be:

#!/usr/bin/env bash
set -e

function checker() { 
        which "$1" | grep -o "$1" > /dev/null &&  return 0 || return 1 
}

if checker "$1" == 0 ; then echo "Installed"; else echo "Not Installed!"; fi

Note several things:

  1. You will have to deal with dependenciy issues while installing
  2. To avoid interaaction with script during install see here for examples.
  3. You can catch the return values from that function an use it to decide whether to install or not.

Tags:

Bash

Apt

Scripts