Issue
I need something in a script to increment a version number: when I have the string 1.0.2
, I want to have a bash command that makes it 1.0.3
.
Something like this but this doesnt work:
CI_COMMIT_TAG=1.0.2
patch=$((CI_COMMIT_TAG + 1)); echo new path=${CI_COMMIT_TAG}
gives this error:
1.0.2: syntax error: invalid arithmetic operator (error token is ".0.2")
Probably because 1.0.2
is a string and not a number.
How to solve this ?
Solution
(imo) The easiest approach would be to split the version number into separate (integer) components, do the math, and then paste back together into the desired version string.
At this point there are several ways to approach this idea.
One idea using some basic commands to implement each of the proposed steps:
CI_COMMIT_TAG=1.0.2
IFS=. read -r v1 v2 v3 <<< "${CI_COMMIT_TAG}" # split into (integer) components
((v3++)) # do the math
patch="${v1}.${v2}.${v3}" # paste back together
This generates:
$ echo "${patch}"
1.0.3
By splitting into the separate (integer) components it'll also be easier if/when you want to increment the first/second component.
Another approach where we let awk
do all the work:
$ awk '
BEGIN {FS=OFS="."} # define input/output field delimiter as "."
{$3++ # increment field #3 "+1" (think "inplace" increment of field #3)
print # print current line
}
' <<< "${CI_COMMIT_TAG}"
1.0.3
# removing comments, collapsing to a one-liner, and storing the result in variable 'patch'
$ patch=$(awk 'BEGIN {FS=OFS="."} {$3++; print}' <<< "${CI_COMMIT_TAG}")
$ echo $patch
1.0.3
NOTE: Both of these solutions assume the 3rd component is an integer otherwise the step of adding '+1' (v3++
/ $3++
) will fail; additional coding could be added to validate the 3rd component is in fact an integer.
Answered By - markp-fuso Answer Checked By - Willingham (WPSolving Volunteer)