我正在尝试检查安装的nginx版本是否与配置文件中定义的版本相同.
我的代码:
#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
这段代码可以工作,但是我遇到了一个问题:
如果版本号更改,则剪切号(在此示例中为nginxv:21)不再适合.
例:
nginx-1.13.12 vs nginx-1.15.0 (13 vs 14 chars)
有什么办法可以使它正常工作,而不会造成麻烦?
解:
我改编了@Mohammad Saleh Dehghanpour的解决方案,它的工作就像一个魅力:
command="nginx -v"
nginxv=$( ${command} 2>&1 )
nginxlocal=$(echo $nginxv | grep -o '[0-9.]*$')
echo $nginxlocal
1.15.0
最佳答案
您可以使用正则表达式而不是cut.例如,要从nginx-1.15.0中提取版本号,请使用:
回声’nginx-1.15.0’| grep -o'[0-9.] * $’
输出:1.15.0