Search code examples
bashshellawksemantic-versioning

Fix shell script to increment semversion


I've never work with shell (bash), but found some bug in script, that I used to increment version. Script works fine, until this case

version=1.27.9
echo $version | awk -F. -v OFS=. 'NF==1{print ++$NF}; NF>1{if(length($NF+1)>length($NF))$(NF-1)++; $NF=sprintf("%0*d", length($NF), ($NF+1)%(10^length($NF))); print}'

1.28.0  <-- result, but I need 1.27.10

In this case new_version will be equals to 1.28.0. How to change this script to avoid incrementing MINOR number? For this case I expecting 1.27.10

I've no experience in shell, so don't know where to start. I found this script here, on SO and use it. Please help me to solve my problem. Thank you in advance.


Solution

  • EDIT: To change only MINOR version try following.

    echo "$version" | awk 'BEGIN{FS=OFS="."} {$3+=1} 1'
    

    Explanation: Adding explanation to above code.

    echo "$version" |           ##using echo to print variable version value here and passing it to awk program.
    awk '                       ##Starting awk program from here.
    BEGIN{                      ##Starting BEGIN section of this awk program here.
      FS=OFS="."                ##Setting FS and OFS as dot(.) here for all lines of Input_file.
    }
    {
      $3+=1                     ##For every line of Input_file adding 1 to 3rd field and saving output to $3 itself.
    }
    1                           ##Mentioning 1 will print edited/non-edited lines here.
    '
    


    Could you please try following, to change middle version as per last(minor) version which OP confirmed not needed but which I understood at very first glance of this requirement.

    echo "$version" | awk 'BEGIN{FS=OFS="."} {$3+=1;if($3>9){$2+=1;$3=0}} 1'