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
Written by Chris Albrecht
Related protips
2 Responses
The interface could be much improved:
-
VERSION_CHECK[0]
should just be the return code of the function. -
VERSION_CHECK[1]
should becomeVERSION_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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Version
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#