Bash-compare-versions: Difference between revisions

From I Will Fear No Evil
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
<metadesc>Bash examples to compare versions</metadesc>
This is a simplistic way to compare version numbers.  This is useful for when commands change over time, and you do not know which or what kind of host will have which version of something.
This is a simplistic way to compare version numbers.  This is useful for when commands change over time, and you do not know which or what kind of host will have which version of something.
* [https://unix.stackexchange.com/questions/269273/bash-convert-a-string-version-number-to-an-integer|Source page with some examples]
* [https://unix.stackexchange.com/questions/269273/bash-convert-a-string-version-number-to-an-integer|Source page with some examples]
Line 26: Line 27:
fi
fi
</pre>
</pre>
If there is a v floating about in your returned string, simply append the following to remove all a-z and A-Z characters.
<pre>
| tr -d [:alpha:]
</pre>
It is important to note that this really IS a string compare and ordering, so watch out for the following:
<pre>
echo -e "2.22\n2.22.0" | sort -V
2.22
2.22.0
</pre>
[[Category:bash]]
[[Category:bash]]

Latest revision as of 15:04, 25 April 2024

This is a simplistic way to compare version numbers. This is useful for when commands change over time, and you do not know which or what kind of host will have which version of something.

echo -e "2.22\n11.3.4" | sort -V
2.22
11.3.4
printf '%s\n2.15\n' $(ldd --version | sed -n '1s/.* //p') | sort -V | head -n 1
printf '%s\n2.22\n' $(git --version | sed -n '1s/.* //p') | sort -V

Example: (show the git branch you are on)

if [[ $(printf '%s\n2.22\n' $(git --version | sed -n '1s/.* //p') | sort -V) != "2.22" ]]; then
  echo "Earlier version than cutoff"
  git rev-parse --abbrev-ref HEAD
else
  echo "Later version of cutoff"
  git branch --show-current
fi

If there is a v floating about in your returned string, simply append the following to remove all a-z and A-Z characters.

| tr -d [:alpha:]

It is important to note that this really IS a string compare and ordering, so watch out for the following:

echo -e "2.22\n2.22.0" | sort -V
2.22
2.22.0