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.
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.
You missed to refer it as a variable like ${DRUSH_VERSION}
instead of "$DRUSH_VERSION"
in if condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With