How do you compare two version strings in Bash?
AdvancedConceptArrays, conditionals and loops
Answer
String comparison fails (1.10 sorts before 1.9). Use GNU sort -V:
version_ge() { # version_ge A B -> true if A >= B
[[ "$(printf '%s\n' "$2" "$1" | sort -V | head -n1)" == "$2" ]]
}
current=$(kubectl version --client -o json | jq -r .clientVersion.gitVersion)
version_ge "${current#v}" 1.29.0 || die "kubectl $current is too old, need >= 1.29"
For strict semver with pre-release tags (1.2.0-rc.1), sort -V is not fully semver-compliant; use a dedicated tool if that matters.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate