if [ "$macOS" >= "$monterey2" ] ; then
Ouputs this error -> "[: 12.2.1: unary operator expected"..
What am I doing wrong?
This happens because [
is a normal command, and so >
works in the usual way as the redirection operator. The word after that, =
, is taken as the file name, and both are removed before they're passed to the [
command. So, if you have in effect e.g.
[ 12.2.1 >= 12.0 ]
, it's similar to [ 12.2.1 12.0 ] > outputfile
, just with an odder filename and more confusing ordering.
[
sees two arguments before the closing ]
, so it expects a unary operator and the operand to it. That would be stuff like e.g. [ -f xyz ]
to check if xyz
is an existing regular file. Of course, 12.2.1
isn't a valid operator, so you get the error. Also, you'll find that file called =
in the directory you ran the script in.
I've tried -eq as well with same result.
Well, it's not the same result, since the error message is "integer expression expected", as you mentioned in the question title. Bash only does integer arithmetic, and your values aren't integers. There's workarounds in How to do integer & float calculations, in bash or other languages/frameworks?
However, as other answers mention, you can't compare version numbers as decimal / floating point numbers anyway. While 12.0
is a number, 12.2.1
isn't.
sort -V
is. It will handle alpha in version numbers too, and allows-f
to fold upper/lower in such cases. – Paul_Pedant Feb 13 '22 at 21:25sort
or[[ a < b ]]
fail same as simple numeric comparisons.sort -V
is another thing entirely, it even supports Debian's tilde-suffixes for pre-versions (1.2~rc1
<1.2
<1.2-foo
). Well, at least the one on Debian does. ;) – ilkkachu Feb 13 '22 at 22:36