1

I've written this function:

function isInstalled {
if [ rpm -q $1 &> /dev/null ]; then
    echo 'installed';
    return 1;
else
    echo 'not installed';
    return 0;
fi
}

But something is wrong. It always returns 0. Even when package is installed. I guess I'm not checking the return signal correctly.

[vagrant@centos-7 ~]$ isInstalled wget2
not installed
[vagrant@centos-7 ~]$ isInstalled wget
not installed

[vagrant@centos-7 ~]$ rpm -q wget
wget-1.14-10.el7_0.1.x86_64
0

3 Answers 3

4

if [ rpm -q ... &> /dev/null ] is invalid use of the [ builtin. You would see this in the error message if you didn't redirect stderr, like this:

if [ rpm -q $1 >/dev/null ]; then

Every command you execute has an exit code, so there's no need for wrapping in [ ... ], and it's invalid syntax.

Write it this way:

isInstalled() {
    if rpm -q $1 &> /dev/null; then
        echo 'installed';
        return 1;
    else
        echo 'not installed';
        return 0;
    fi
}
1

Your function should be written as

isInstalled() {
    if rpm -q "$1" >/dev/null ; then
        echo "installed"
        return 0
    else
        echo "not installed"
        return 1
    fi
}

Notes:

  • The more portable syntax for defining a function is just

    function_name() {
        …
    }
    
  • The square brackets [ ] are only for specific kinds of tests, such as for whether a string is empty. You don't need them to check the exit status of a command.

  • Your redirection syntax is wrong.

  • In shell programming, it is customary to return a zero status for success, and a non-zero status for failure. Therefore, you should swap your return values.

  • You should almost always use double-quotes whenever referencing any variable. Otherwise, your scripts will break (possibly in security-compromising ways) with unexpected input (such as a space character in the parameter).

0
function isInstalled {
    rpm -q $1 &> /dev/null;

    if [ $? == 0 ]; then
            return true;
    else
            return false;
    fi
}

Test: if [ isInstalled wget ]; then echo 'installed'; else echo 'not installed'; fi

1
  • Actually, your test is also invalid, just like the code in your question. See my explanation in my answer
    – janos
    Dec 25, 2014 at 20:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .