Bash:Nginx 版本检查剪切

Aer*_*ris 3 bash cut nginx

我正在尝试检查安装的 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
Run Code Online (Sandbox Code Playgroud)

此代码“可以”工作,但我遇到了一个问题:如果版本号更改,则剪切号(nginxv:21在本例中)不再适合。

例子:

nginx-1.13.12 vs nginx-1.15.0 (13 vs 14 chars)
Run Code Online (Sandbox Code Playgroud)

有没有办法让它工作,没有那个麻烦?

解决方案: 我改编了@Mohammad Saleh Dehghanpour 的解决方案,它的效果非常好:

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

echo $nginxlocal
1.15.0
Run Code Online (Sandbox Code Playgroud)

Sal*_*leh 6

您可以使用正则表达式代替 cut。例如从nginx-1.15.0使用中提取版本号:

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

输出: 1.15.0