CR47
CR47

Reputation: 923

How can I check for software versions in a shell script?

I have two software version checks in my bash script that don't work as I would have expected.

DRUSH_VERSION="$(drush --version)"
echo ${DRUSH_VERSION}
if [[ "$DRUSH_VERSION" == "Drush Version"* ]]; then
    echo "Drush is installed"
  else
    echo "Drush is NOT installed"
fi
GIT_VERSION="$(git --version)"
echo ${GIT_VERSION}
if [[ "GIT_VERSION" == "git version"* ]]; then
    echo "Git is installed"
  else
    echo "Git is NOT installed"
fi

Response:

Drush Version : 6.3.0
Drush is NOT installed
git version 1.8.5.2 (Apple Git-48)
Git is NOT installed

Meanwhile, if I change

DRUSH_VERSION="${drush --version)"

to

DRUSH_VERSION="Drush Version : 6.3.0"

it responds with

Drush is installed

For now I will use

if type -p drush;

but I would still like to get the version number.

Upvotes: 7

Views: 14829

Answers (2)

Swapna Avula
Swapna Avula

Reputation: 11

You missed to refer it as a variable like ${DRUSH_VERSION} instead of "$DRUSH_VERSION" in if condition.

Upvotes: 1

David C. Rankin
David C. Rankin

Reputation: 84642

There are a couple of issues you can fix. First, if you are not concerned with portability, then you want to use the substring match operator =~ instead of ==. That will find git version within git version 1.8.5.2 (Apple Git-48). Second you are missing a $ in your [[ "GIT_VERSION" == "git version" ]] test.

So, for example, if you change your tests as follows, you can match substrings. (Note: the =~ only works with the [[ ]] operator, and you will need to remove any wildcards *).

if [[ "$DRUSH_VERSION" =~ "Drush Version" ]]; then
...
if [[ "$GIT_VERSION" =~ "git version" ]]; then
...

Additionally, if you are just checking for the existence of a program and not the specific version number, then you are probably better off using:

if which $prog_name 2>/dev/null; then...

or using a compound command:

which $prog_name && do something found || do something not found

E.g. for git:

if which git 2>/dev/null; then
...

or

which git && echo "git found" || echo "git NOT found"

Note: the redirection of stderr into /dev/null just prevent the error from spewing across the screen in the case that $prog_name is NOT present on the system.

Upvotes: 6

Related Questions