當你寫了一個shell腳本,想使用腳原本比較兩個版本號,而後能區分哪一個版本號更高哪一個版本號更低。好比,你安裝某個軟件的時候,要求是版本號要大於1.3.0,想驗證最低配置要求.又或者你想在shell腳本中寫版本號判斷(好比版本號若是介入1.0.0 ≤ 版本 ≤ 2.3.1).bash
若是你想經過shell來比較兩個版本號字符串的話最簡單的就是使用sort命令。加上參數"-V"後sort命令就能夠把文本中的版本號給排序出來(默認是遞增的排序),而後你想倒敘排序的話那就使用參數"-rV"便可.less
下面咱們就來看下在shell中怎麼使用sort命令來比較版本號吧函數
對於要比較版本號字符串的話,下面的這些使用了sort命令的自定義函數可能會派上用場.spa
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"; }
上面的腳本主要是比較兩個不一樣版本的文本,會得出大於、等於、小於、大於等於等結果。你能夠根據本身的須要使用自定義函數。code
下面是一個比較的示例.blog
#!/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