1

we need to test and compare java versions

any suggestion for tricky way how to verify if $version > $New_version ?

[root@master tmp]# version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}') [root@master tmp]# echo $version 1.8.0_65 [root@master tmp]# New_version=1.8.0_111 [root@master tmp]# [[ $version > $New_version ]] && echo ok ok [root@master tmp]# 
0

    1 Answer 1

    2

    Use GNU sort's version-sort along with the "check if input is sorted" option:

    printf '%s\n%s\n' "$version" "$New_version" | sort -rVc 2>/dev/null && echo ok 

    The 2>/dev/null is to drop sort's complaint when the input is not sorted; you just want to know if it's sorted or not, which is reflected in the return code.

    Sample run:

    $ version=1.8.0_65 $ New_version=1.8.0_111 $ printf '%s\n%s\n' "$version" "$New_version" | sort -rVc 2>/dev/null && echo ok $ version=1.8.0_650 $ printf '%s\n%s\n' "$version" "$New_version" | sort -rVc 2>/dev/null && echo ok ok $ 

    Alternatively, do it the hard way:

    oldstr=${old//./ } oldstr=${oldstr//_/ } newstr=${new//./ } newstr=${newstr//_/ } read -a oldarr <<< "$oldstr" read -a newarr <<< "$newstr" [ ${oldarr[0]} -ge ${newarr[0]} ] && [ ${oldarr[1]} -ge ${newarr[1]} ] && [ ${oldarr[2]} -ge ${newarr[2]} ] && [ ${oldarr[3]} -gt ${newarr[3]} ] && echo OK 

    This sets up new variables where we replace all of the dots and underscores with spaces, then feed those as here-strings into read to split them into arrays, then we compare each element of the parallel arrays.

    2
    • can we do printf '%s\n%s\n' "$version" "$New_version" | sort -rVc 2>/dev/null && status=ok || status=fail ?
      – yael
      CommentedDec 11, 2018 at 15:11
    • you could, since the variable assignment will (should) always succeed, so it won't accidentally trigger the failure-branch's assignment. If it was me, I'd spell it out with an if printf ... | sort ...; then status=ok; else status=fail; fi, for clarity
      – Jeff Schaller
      CommentedDec 11, 2018 at 15:24

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.