create new directory with incremental version using bash

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error create new directory with incremental version using bash on this date .

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 "%fn" | 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))

Answer

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