Math operations on bash scripts working on both Mac zsh and ubuntu bash

Elvis Ciotti
2 min readApr 16, 2024

To run math operations on bash, on any shell, the best way I found is via awk.

when pasing an argument BEGIN { print <operation> } , it’ll basically output the math operation result, where the variables are of course replaced by bash.

Basic example

awk “BEGIN {print 1 + 1}”

will print 2 .

Use variables as input

Variables can of course be injected in the string as any other shell string.

So this

export VAR1=1
awk "BEGIN {print ${VAR1} + 1}" // 2

will also output 2

Capture output into another variable

the $() shell operator captures a command output into a variable, so here an example

export VAR1=0
VAR1=$(awk "BEGIN {print ${VAR1} + 2}")
echo $VAR1 // 2

Other usefuloperations

  • + (plus)
  • - (minus)
  • / (division)
  • ^ (exponentiation)
  • * (multiplication),
  • % (modulus)
  • ++Variable or — Variable for increment/decrement
  • log( x ) Returns the natural logarithm of x
  • sqrt( x ) Returns the square root of x
  • rand( ) Returns a random number n, with 0 <= n < 1.
  • sub( Ere, Repl, [ In ] ) Replaces the first occurrence of the extended regular expression specified by the Ere parameter in the string specified by the In parameter with the string specified by the Repl parameter. The sub function returns the number of substitutions. An & (ampersand) appearing in the string specified by the Repl parameter is replaced by the string in the In parameter that matches the extended regular expression specified by the Ere parameter. If no In parameter is specified, the default value is the entire record ( the $0 record variable)
  • substr( String, M, [ N ] ) Returns a substring with the number of characters specified by the N parameter. The substring is taken from the string specified by the String parameter, starting with the character in the position specified by the M parameter. The M parameter is specified with the first character in the String parameter as number 1. If the N parameter is not specified, the length of the substring will be from the position specified by the M parameter until the end of the String parameter.

Conditional statements and more advanced control flow is available. see here https://www.ibm.com/docs/en/aix/7.2?topic=awk-command

--

--

Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://www.linkedin.com/in/elvisciotti