Archive for June 2022
Compare versions in bash - vercomp {}
Posted on Fri, Jun 24, 2022 at 17:23 by Hubertus A. Haniel
I have taken this from https://stackoverflow.com/a/4025065/1763937 and it can also be found at https://github.com/f-o-a-m/cliquebait/blob/master/vercomp.bash
I have put a copy of it here for my own reference mostly as I think this is a really good pice of code and I have used it in a few scripts now:
#!/bin/bash vercomp () { if [[ $1 == $2 ]] then return 0 fi local IFS=. local i ver1=($1) ver2=($2) # fill empty fields in ver1 with zeros for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)) do ver1[i]=0 done for ((i=0; i<${#ver1[@]}; i++)) do if [[ -z ${ver2[i]} ]] then # fill empty fields in ver2 with zeros ver2[i]=0 fi if ((10#${ver1[i]} > 10#${ver2[i]})) then return 1 fi if ((10#${ver1[i]} < 10#${ver2[i]})) then return 2 fi done return 0 } testvercomp () { vercomp $1 $2 case $? in 0) op='=';; 1) op='>';; 2) op='<';; esac if [[ $op != $3 ]] then echo "FAIL: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'" else echo "Pass: '$1 $op $2'" fi } # Run tests # argument table format: # testarg1 testarg2 expected_relationship echo "The following tests should pass" while read -r test
do
testvercomp $test
done << EOF
1 1 = 2.1 2.2 < 3.0.4.10 3.0.4.2 > 4.08 4.08.01 < 3.2.1.9.8144 3.2 > 3.2 3.2.1.9.8144 < 1.2 2.1 < 2.1 1.2 > 5.6.7 5.6.7 = 1.01.1 1.1.1 = 1.1.1 1.01.1 = 1 1.0 = 1.0 1 = 1.0.2.0 1.0.2 = 1..0 1.0 = 1.0 1..0 = EOF echo "The following test should fail (test the tester)" testvercomp 1 1 '>'
Now when you run the code:
$ . ./vercomp The following tests should pass Pass: '1 = 1' Pass: '2.1 < 2.2' Pass: '3.0.4.10 > 3.0.4.2' Pass: '4.08 < 4.08.01' Pass: '3.2.1.9.8144 > 3.2' Pass: '3.2 < 3.2.1.9.8144' Pass: '1.2 < 2.1' Pass: '2.1 > 1.2' Pass: '5.6.7 = 5.6.7' Pass: '1.01.1 = 1.1.1' Pass: '1.1.1 = 1.01.1' Pass: '1 = 1.0' Pass: '1.0 = 1' Pass: '1.0.2.0 = 1.0.2' Pass: '1..0 = 1.0' Pass: '1.0 = 1..0' The following test should fail (test the tester) FAIL: Expected '>', Actual '=', Arg1 '1', Arg2 '1'Edited on: Mon, Oct 10, 2022 12:43
Posted in Shell Scripting (RSS)
function cleanexit {} - Clean your shit!
Posted on Mon, Jun 20, 2022 at 11:42 by Hubertus A. Haniel
When writing shell scripts in bash that create temporary files I prefer to stick a clean exit function at the top of the script that runs the clean up no matter how the script exits - this should even remove files when the script got interrupted:
function cleanexit
{
rm -f /var/tmp/tmpfile
}
trap cleanexit INT QUIT TERM EXIT
Let me know if you have a better idea!
Edited on: Wed, Aug 02, 2023 14:36Posted in HowTo (RSS), Shell Scripting (RSS), System - AIX (RSS), System - Linux (RSS), System - Solaris (RSS)