How to increment version number in a shell script?

前端 未结 11 2058
执念已碎
执念已碎 2020-11-29 23:47

The following simple version control script is meant to find the last version number of a given file, increment it, run a given command with the newly created file (e.g., ed

11条回答
  •  独厮守ぢ
    2020-11-30 00:26

    1. Only increment the selected part

    Usage

    increment_version 1.39.0 0 # 2.39.0
    increment_version 1.39.0 1 # 1.40.0
    increment_version 1.39.0 2 # 1.39.1
    

    Code

    ### Increments the part of the string
    ## $1: version itself
    ## $2: number of part: 0 – major, 1 – minor, 2 – patch
    increment_version() {
      local delimiter=.
      local array=($(echo "$1" | tr $delimiter '\n'))
      array[$2]=$((array[$2]+1))
      echo $(local IFS=$delimiter ; echo "${array[*]}")
    }
    

    Simplified version of @dimpiax answer


    EDIT: I created another version of this script that put zeros on the less important parts if the most important ones are changed. Just note the diferent expected results on the usage part.

    2. Increment the selected part and put zeros on the subsequent parts

    Usage

    increment_version 1.39.3 0 # 2.0.0
    increment_version 1.39.3 1 # 1.40.0
    increment_version 1.39.3 2 # 1.39.4
    
    #!/bin/bash
    
    ### Increments the part of the string
    ## $1: version itself
    ## $2: number of part: 0 – major, 1 – minor, 2 – patch
    
    increment_version() {
      local delimiter=.
      local array=($(echo "$1" | tr $delimiter '\n'))
      array[$2]=$((array[$2]+1))
      if [ $2 -lt 2 ]; then array[2]=0; fi
      if [ $2 -lt 1 ]; then array[1]=0; fi
      echo $(local IFS=$delimiter ; echo "${array[*]}")
    }
    

提交回复
热议问题