0

I have to maintain versioning of different files in one text file. for example :- if there are 2 files abc-1.0.0.jar and def-1.0.0.jar

so when i run the command this filename with version should be copied inside the text file (lets call it version.txt)

so output of cat version.txt should show the two files abc-1.0.0.jar def-1.0.0.jar

and when the next version (say 2.0.0) of file gets deployed , the version should also get updated in the text file

cat version.txt

abc-2.0.0.jar def-2.0.0.jar

I tried this but not able to update for both file in same text file..

artifact= abc
version= 1.0.0
echo "$artifact-$version" > version.txt

but above command will keep only one one file and if i give below command :- echo "$artifact-$version" >> version.txt then this will keep on adding all the versions. but i need only the updated version for the matching file

Please let me know how to solve this problem.

garima
  • 53
  • 1
  • 9

1 Answers1

0

Hopefully this is useful to you.

#!/bin/bash
compare_versions () {
    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
}

echo "Version list" > version.txt
filename=($(ls -1 *.jar | sed -e 's/\.jar$//' | cut -d"-" -f1 | uniq))
for f in ${filename[@]}; do
    ver=($(ls -1 $f* | sed -e 's/\.jar$//' | cut -d"-" -f2))
    v1=${ver[0]}
    for ((i=1; i<${#ver[@]}; i++)); do
        v2=${ver[$i]}
        compare_versions $v1 $v2 '<'
        if [ $? -eq "2" ]; then
            v1=$v2
        fi
    done
    echo  "updated version of $f is $v1" >> version.txt 
done

Here were the files I tested against

abc-0.0.1.jar  abc-1.0.0.jar  abc-1.0.1.jar  abc-2.0.0.jar  cde-1.0.0.jar  cde-1.0.1.jar

and here is the output of version.txt

Version list
updated version of abc is 2.0.0
updated version of cde is 1.0.1

I did get a little inspired by this answer https://stackoverflow.com/a/4025065/13876104 and used the vercomp function. (thanks!)