Robert Grantham
Robert Grantham

Reputation: 13

How to make a bash script to check if a program or library exists

I want to make a function to check if the program or library is already installed.

Thats what I do now:

dpkg --status software-properties-common | grep -q not-installed
if [ $? -eq 0 ]; then
    sudo apt-get install -y software-properties-common
fi

What I want:

isPackageNotInstalled() {???} 

if [ $(isPackageNotInstalled 'software-properties-common') ]; then 
   sudo apt-get install -y software-properties-common
fi

any help would be greatly appreciated.

Upvotes: 1

Views: 2692

Answers (3)

Tek aEvl
Tek aEvl

Reputation: 1

This script works in #archlinux also, based on the the answer already chosen.

isPackageNotInstalled() {

    pacman -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    sudo pacman -S $1
    fi
    }

isPackageNotInstalled $1

for yaourt

isPackageNotInstalled() {

    yaourt -Ss $1 &&> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    yaourt -S $1
    fi
    }

isPackageNotInstalled $1

Upvotes: 0

GAD3R
GAD3R

Reputation: 4625

A sample script including a function to check and install the missing package:

#!/bin/bash

isPackageNotInstalled() {

    dpkg --status $1 &> /dev/null
    if [ $? -eq 0 ]; then
    echo "$1: Already installed"
    else
    sudo apt-get install -y $1
    fi
    }

isPackageNotInstalled $1

save it as script , usage ./script package_name.

man dpkg :

EXIT STATUS
       0      The requested action was successfully performed.  Or a check  or
              assertion command returned true.

       1      A check or assertion command returned false.

       2      Fatal  or unrecoverable error due to invalid command-line usage,
              or interactions  with  the  system,  such  as  accesses  to  the
              database, memory allocations, etc.

Upvotes: 2

Alan
Alan

Reputation: 31

I see that dpkg --status has several return values that can imply partially-installed or pending packages. My thought would be to use its return code rather than checking for any particular text. Full disclosure - I can't try this with actual dpkg right now, but something quick you can try....

So for a simple command:

if ! (dpkg --status "..." &>/dev/null); then ...

or more simply:

dpkg --status "..." &>/dev/null || sudo apt-get ...

and to put it in a function:

function isPackageNotInstalled() { ! dpkg --status "$1" &>/dev/null }

then to use it:

if isPackageNotInstalled "..."; then ...

or, as above, just:

isPackageNotInstalled "..." && sudo apt-get ...

Hope this helps.

Upvotes: 1

Related Questions