Thursday, November 18, 2021

[SOLVED] Bash: Nginx Version check cut

Issue

I'm trying to check if the installed nginx version is equal with the version defined in a config file.

My code:

#check version

command="nginx -v"
nginxv=$( ${command} 2>&1 )
nginxvcutted="echo ${nginxv:21}"
nginxonpc=$( ${nginxvcutted} 2>&1 )

if [ $nginxonpc != ${NGINX_VERSION} ]; then
  echo "${error} The installed Nginx Version $nginxonpc is DIFFERENT with the Nginx Version ${NGINX_VERSION} defined in the config!"
else
    echo "${ok} The Nginx Version $nginxonpc is equal with the Nginx Version ${NGINX_VERSION} defined in the config!"
fi

This code 'can' work, but I have got a problem: If the version number changes, the cut number (nginxv:21 in this example) doesn't fit anymore.

Example:

nginx-1.13.12 vs nginx-1.15.0 (13 vs 14 chars)

Is there any way to get this working, without that trouble?

Solution: I adapted the solution from @Mohammad Saleh Dehghanpour and it's working like a charm:

command="nginx -v"
nginxv=$( ${command} 2>&1 )
nginxlocal=$(echo $nginxv | grep -o '[0-9.]*$')

echo $nginxlocal
1.15.0

Solution

You can use regular expression instead of cut. For example to extract version number from nginx-1.15.0 use:

echo 'nginx-1.15.0' | grep -o '[0-9.]*$'

Output: 1.15.0



Answered By - Saleh