Friday, November 22, 2013

Operator Mathematics in bash scripting

When we talking about programming, we can't off with operator mathematics.
In Bash scripting, there are 3 ways to use operator mathematics.

  1. let
  2. expr
  3. substitution
let's us try to combine the 3 ways that we know in one script


#!/bin/bash
#math1

a=10
b=5
#use let
let add=$a+$b
let min=$a-$b
let multiple=$a*$b

#memakai expr
divide=`expr $a / $b`

#use substitution command $((expresion))
mod =$(($a%$b))  #modulus

echo "$a+$b=$add"
echo "$a-$b=$min"
echo "$a*$b=$multiple"
echo "$a/$b=$divide"
echo "$a%$b=$mod"


Below is the result

[elvin@Testbed$]./mat1
10+5=15
10-5=5
10*5=50
10/5=2
10%5=0

for expr function it is also useful for string
example
[elvin@Testbed$]mystr="linux"
[elvin@Testbed$]expr length $mystr
5


0 comments:

Post a Comment