How to increment version number in a shell script?

前端 未结 11 2091
执念已碎
执念已碎 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:25

    Pure Bash:

    increment_version ()
    {
      declare -a part=( ${1//\./ } )
      declare    new
      declare -i carry=1
    
      for (( CNTR=${#part[@]}-1; CNTR>=0; CNTR-=1 )); do
        len=${#part[CNTR]}
        new=$((part[CNTR]+carry))
        [ ${#new} -gt $len ] && carry=1 || carry=0
        [ $CNTR -gt 0 ] && part[CNTR]=${new: -len} || part[CNTR]=${new}
      done
      new="${part[*]}"
      echo -e "${new// /.}"
    } 
    
    version='1.2.3.44'
    
    increment_version $version
    

    result:

    1.2.3.45
    

    The version string is split and stored in the array part. The loop goes from the last to the first part of the version. The last part will be incremented and possibly cut down to its original length. A carry is taken to the next part.

提交回复
热议问题