一、场景介绍
在软件开发过程中,特别是版本部署或者别的业务场景逻辑中,都需要对同一个应用的不同版本做部署或者应用操作。这时候需要使用版本号来做业务控制。比如:在容器化部署过程中,每次部署相同应用的时候,都需要部署容器仓库中最新版本的镜像到本地容器。
二、操作方法
-
脚本操作
[root@node100 build]# sort -V no.txt | sed '/p-/d' > sort.txt [root@node100 build]# cat sort.txt 1.0.0.1 1.0.0.2 1.0.0.3 1.0.0.4 1.0.0.5 1.0.0.6 1.0.0.7 1.0.0.8 1.0.0.9 [root@node100 build]# sort -rV no.txt | sed '/p-/d' > sort.txt [root@node100 build]# cat sort.txt 1.0.0.9 1.0.0.8 1.0.0.7 1.0.0.6 1.0.0.5 1.0.0.4 1.0.0.3 1.0.0.2 1.0.0.1 [root@node100 build]#
-
获取最新的版本号(获取排序后文件中的第一行)
# 获取最新的版本号 lastestversion=`sed -n '1p' sort.txt`
-
比较版本号自定义函数
-
函数定义
function version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; } function version_le() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" == "$1"; } function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" != "$1"; } function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; }
-
使用示例
#!/bin/bash VERSION=$1 VERSION2=$2 function version_gt() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; } function version_le() { test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" == "$1"; } function version_lt() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" != "$1"; } function version_ge() { test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1"; } if version_gt $VERSION $VERSION2; then echo "$VERSION is greater than $VERSION2" fi if version_le $VERSION $VERSION2; then echo "$VERSION is less than or equal to $VERSION2" fi if version_lt $VERSION $VERSION2; then echo "$VERSION is less than $VERSION2" fi if version_ge $VERSION $VERSION2; then echo "$VERSION is greater than or equal to $VERSION2" fi
-