Interview Prep/Shell Scripting/Arrays, conditionals and loops

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops