Last Updated: February 25, 2016
·
1.067K
· keyboardcowboy

Version Requirements Check in Bash

This little function will make it simple to check if a given utility meets the minimum version requirements for your script.

The Function

# Compare multipoint versions
function check_min_version {
  local BASE=$1
  local MIN=$2

  # Break apart the versions into an array of semantic parts
  local BASEPARTS=(${BASE//./ })
  local MINPARTS=(${MIN//./ })

  # Ensure there are 3 parts (semantic versioning)
  if [[ ${#BASEPARTS[@]} -lt 3 ]] || [[ ${#MINPARTS[@]} -lt 3 ]]; then
    VERSION_CHECK_ERROR="Please provide version numbers in semantic format MAJOR.MINOR.PATCH."
    return
  fi

  # Compare the parts
  if [[ ${BASEPARTS[0]} -lt ${MINPARTS[0]} ]] || [[ ${BASEPARTS[0]} -eq ${MINPARTS[0]} && ${BASEPARTS[1]} -lt ${MINPARTS[1]} ]] || [[ ${BASEPARTS[0]} -eq ${MINPARTS[0]} && ${BASEPARTS[1]} -eq ${MINPARTS[1]} && ${BASEPARTS[2]} -lt ${MINPARTS[2]} ]]; then
    VERSION_CHECK_ERROR="Minimum version required is $MIN.  Your's is $BASE."
  fi
}

How to Use It

# Check drush version.  Must be >= 6.4.
check_min_version `drush --version --pipe` "6.4.0"
if [[ -n "$VERSION_CHECK_ERROR" ]]; then
  echo -e "$VERSION_CHECK_ERROR"
  exit 1
fi

2 Responses
Add your response

The interface could be much improved:

  • VERSION_CHECK[0] should just be the return code of the function.
  • VERSION_CHECK[1] should become VERSION_ERROR and be set only if an error occured.
over 1 year ago ·

Thanks, dolmen. I took your advice and simplified it even further, removing VERSION_CHECK altogether and using just VERSION_CHECK_ERROR to determine if the requirements had been met or not. Much simpler now.

over 1 year ago ·