1

I need to generate new directories in incremental fashion. Below is the folder structure:-

1. Dockerfile
2. Makefile
3. manifests
    + 1.0.0
    + 1.0.1   

I want to fetch the latest version from the existing directories in a variable i.e. last=1.0.1, add the value 0.0.1 to last to get the next version i.e next=1.0.2. So that I can create a new directory using mkdir manifests/$next, something like this:-

1. Dockerfile
2. Makefile
3. manifests
    + 1.0.0
    + 1.0.1
    + 1.0.2   

I am able to fetch the directory name with the latest version using the below command:-

last=$(find manifests -type d -name '[0-9]*.[0-9]*.[0-9]*' -printf "%f\n" | sort -V | tail -n 1)

How do I add 0.0.1 to the variable, so that next=1.0.2 something like this:-

next=$(($last + 0.0.1))
Rishab Prasad
  • 771
  • 1
  • 8
  • 21
  • 2
    Does this answer your question? [How to increment version number in a shell script?](https://stackoverflow.com/questions/8653126/how-to-increment-version-number-in-a-shell-script) – Léa Gris Aug 02 '20 at 11:22

3 Answers3

3

With a function for every increment:

#!/bin/bash

next() {
  local l="$1"
  local a="$2"
  local l1 l2 l3 a1 a2 a3

  IFS="." read l1 l2 l3 <<< "$l"
  IFS="." read a1 a2 a3 <<< "$a"
  
  echo "$(($l1+a1)).$(($l2+a2)).$(($l3+a3))"
}

last="1.0.1"
add="0.0.1"

new=$(next "$last" "$add")
echo "$new"

Output:

1.0.2
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 2
    Usually when you increment the major, you reset the minor and the patch number to 0. When you increment minor, you reset the patch number to 0 as well. – Léa Gris Aug 02 '20 at 11:27
  • @LéaGris: Yes, this is a feature that could be added if necessary. – Cyrus Aug 02 '20 at 17:51
2

With plain bash and GNU utilities:

#!/bin/bash

cd manifests || exit
last=$(printf "%s\n" [0-9]*.*.*[0-9]/ | sort -Vr | head -n 1)
last=${last%?} # Remove the last character, that is, the '/'
[[ -d $last ]] && mkdir "${last%.*}.$(( ${last##*.} + 1))"

Run it from the parent directory of manifests.
It finds the latest version by doing a version sort on directories containing at least two dots and beginning and ending with a digit. Then it increments (by one) the part coming after the last dot of the latest version found (it assumes that part is an integer number).

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
1

You can do it with awk:

next=`echo "$last" | awk -F. '{print $1"."$2"."($3+1)}'`
Doj
  • 1,244
  • 6
  • 13
  • 19