Home > OS >  How to do a minus operation in bash with unknown variable type
How to do a minus operation in bash with unknown variable type

Time:10-07

I have a semver version as a string and I want to take the patch version and do math on it. But I just can't figure this out.

This is what I have tried:

#!/bin/bash

version="appVersion=1.3.15"
version=${version##*=} # "1.3.15"
semver=( ${version//./ } ) # ["1", "3", "15"]
patch="${semver[2]}" # "15"

# So far so good.
echo $patch # 15

# This fails. I have no clue how to get the patch variable to be of the correct type
previous=${patch - 1}
echo $previous

CodePudding user response:

For arithmetic operations in bash, you need to use Double Parentheses. Please, check this Arithmetic Expansion section of bash manual

So your code should be:

previous=$((patch-1))

Or as Benjamin W. well suggested in a comment:

((previous = patch - 1))

Output:

root@:~# bash test.sh
15
14
  •  Tags:  
  • bash
  • Related