Ana Sayfa / Linux / Bash Script / Bash Arithmetic

Bash Arithmetic

Parameter Details
EXPRESSION Expression to evaluate

Simple arithmetic with (( ))

#!/bin/bash
echo $(( 1 + 2 ))

Output: 3

# Using variables
#!/bin/bash
var1=4
var2=5
((output=$var1 * $var2))
printf "%d\n" "$output"

Output: 20

Arithmetic command

  • let
let num=1+2
 let num="1+2"
 let 'num= 1 + 2'
 let num=1 num+=2

You need quotes if there are spaces or globbing characters. So those will get error:

let num = 1 + 2 #wrong
let 'num = 1 + 2' #right
let a[1] = 1 + 1 #wrong
let 'a[1] = 1 + 1' #right
  • (( ))
((a=$a+1)) #add 1 to a
((a = a + 1)) #like above
((a += 1)) #like above

We can use (()) in if. Some Example:

if (( a > 1 )); then echo "a is greater than 1"; fi

The output of (()) can be assigned to a variable:

result=$((a + 1))

Or used directly in output

echo "The result of a + 1 is $((a + 1))"

Simple arithmetic with expr

#!/bin/bash
expr 1 + 2

Output: 3

Bunada Göz Atın

PHP Types

Type Comparison There are two types of comparison: loose comparison with == and strict comparison …

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir