bream
bream

Reputation: 168

Trouble using if statement in bash script to check if package installed

I am new to Bash scripting and having difficulty writing this function that I want to use to check if a package is installed or not. My code is:

#!/bin/bash

function is_installed() {
    if [ -n $(dpkg -l | awk "/^ii  $1/")]; then
        echo 1;
    fi
    echo 0;
}

if is_installed "coreutils"; then
    echo "coreutils installed";
else
    echo "coreutils not installed";
fi

Instead of the expected behavior of printing only "coreutils installed", this prints "0", then "1", then "coreutils installed" into the terminal. I think I am not understanding something about Bash syntax here, particularly with complicated if-thens. Any help?

Upvotes: 2

Views: 1936

Answers (1)

Socowi
Socowi

Reputation: 27185

if command checks the exit status of command and not its output. Therefore you should change echo x (= output x) to return x (= exit function with status code x).

is_installed() {
    if [ -n "$(dpkg -l | awk "/^ii  $1/")" ]; then
        return 1;
    fi
    return 0;
}

This can also be shortened to

is_installed() {
    [ -z "$(dpkg -l | awk "/^ii  $1/")" ]
}

For further improvements of the actual check, see Cyrus' comment:

is_installed() {
     dpkg --verify "$1" 2>/dev/null
}

Upvotes: 4

Related Questions