This Gist contains handy snippets for extracting just the version number from various application version strings.
At the time of writing, the majority of these snippets were created for applications installed on a MAC via Homebrew. Please feel free to provide snippets for unsupported setups if required.
# Standard version string
$ nginx -v
nginx version: nginx/1.17.7
# Version number only
$ nginx -v 2>&1 | grep -o '[0-9.]*$'
1.17.7
# Standard version string
$ php -v
PHP 7.3.9 (cli) (built: Nov 9 2019 08:08:13) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.9, Copyright (c) 1998-2018 Zend Technologies
# Version number only
$ php -v | awk '/^PHP/ { print $2 }'
7.3.9
# Standard version string
$ mysql -V
mysql Ver 8.0.18 for osx10.15 on x86_64 (Homebrew)
# or
mysql Ver 14.14 Distrib 5.7.28, for osx10.15 (x86_64) using EditLine wrapper
# Version number only
# Formatted
mysqlVersionString=$(mysql -V)
mysqlVersionNum=$(echo $mysqlVersionString | awk '/Distrib/ { print $5 }');
if [ -z "$mysqlVersionNum" ]; then
mysqlVersionNum=$(echo $mysqlVersionString | awk '/Ver/ { print $3 }');
fi
if [ -z "$mysqlVersionNum" ]; then
mysqlVersionNum='Unknown';
fi
echo "${mysqlVersionNum//[!0-9.]/}";
# Compressed (for script)
vS=$(mysql -V) v=$(echo $vS | awk '/Distrib/ { print $5 }'); if [ -z "$v" ]; then v=$(echo $vS | awk '/Ver/ { print $3 }'); fi; if [ -z "$v" ]; then v='Unknown'; fi; echo "${v//[!0-9.]/}";
# Compressed (for prompt)
# - Escape the ! in the final echo
vS=$(mysql -V) v=$(echo $vS | awk '/Distrib/ { print $5 }'); if [ -z "$v" ]; then v=$(echo $vS | awk '/Ver/ { print $3 }'); fi; if [ -z "$v" ]; then v='Unknown'; fi; echo "${v//[\!0-9.]/}";