I have a variable VarExp with following 2 values
1.5.2
1.5.3
I have another variable VarCurr with following 1 value
1.8.1
I want to compare VarCurr with VarExp and want to echo SUCCESS only when
VarCurr >= VarExp
I have written the following code but it it always returning FAILURE
VarExp='1.5.2 1.5.3'
VarCurr='1.8.1'
printf -v versions '%s\n%s' "$VarExp" "$VarCurr"
if [[ $versions = "$(sort -V <<< "$versions")" ]]; then
echo 'FAILURE'
else
echo 'SUCCESS'
fi
VarCurr need to be >= the lowest value contained in VarExp
I recommend using a language that can properly objectify version objects and can understand major.minor.build.revision. Here's an example bash script which borrows from Perl for version parsing:
#!/bin/bash
VarExp='1.5.2 1.5.3'
VarCurr='1.8.1'
for i in $VarExp; do {
perl -e 'use version;exit !(version->parse('$VarCurr') >= version->parse('$i'));' && {
echo 'SUCCESS'
exit
}
}; done
echo 'FAILURE'
exit
Of course it might be more graceful just to write the whole thing in Perl.
Edit: Here's another example using Python:
#!/bin/bash
VarExp='1.5.3 1.5.6'
VarCurr='1.5.3'
for i in $VarExp; do {
python -c 'from distutils.version import LooseVersion;\
exit(LooseVersion("'$VarCurr'") >= LooseVersion("'$i'"))' || {
echo 'SUCCESS'
exit
}
}; done
echo 'FAILURE'
exit
With GNU sort for -V:
$ cat tst.sh
#!/bin/bash
varExp='1.5.2 1.5.3'
varCurr=$1
minVarExp=$(printf '%s\n' $varExp | sort -V | head -1)
maxOfVers=$(printf '%s\n' "$minVarExp" "$varCurr" | sort -V | tail -1)
if [[ $maxOfVers = $varCurr ]]; then
echo 'SUCCESS'
else
echo 'FAILURE'
fi
$ ./tst.sh 1.8.1
SUCCESS
$ ./tst.sh 1.5.1
FAILURE
$ ./tst.sh 1.5.2
SUCCESS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With