Numbers and Arithmetic in bash: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 50: Line 50:
=Decrement an Integer=
=Decrement an Integer=


<pre>
<syntaxhighlight lang='bash'>
local i=1
local i=1
((i--))
((i--))
</pre>
</syntaxhighlight>
 
=Numeric Evaluation in a Condition=
 
<syntaxhighlight lang='bash'>
local a=1
local b=2
if [[ $(eval ${a} - ${b}) < 0 ]]; then
  ...
fi
</syntaxhighlight>


=Random Numbers=
=Random Numbers=


{{Internal|Bash script that generates a random MAC address|Bash script that generates a random MAC address}}
{{Internal|Bash script that generates a random MAC address|Bash script that generates a random MAC address}}

Revision as of 04:31, 11 December 2019

Internal

How to Tell if a Variable has an Integer Value

v=10

if expr ${v} + 1 >/dev/null 2>&1; then
    #
    # the value contained by v is an integer
    #
else
    #
    # the value contained by v is NOT an integer
    #
fi

More about

expr

Floating Point Operations

Multiplication:

local operand1=10.1
local operand2=20.2

result=$(echo ${operand1} ${operand2} | awk '{printf "%5.1f\n",$1*$2}') || exit 1

Division:

local operand1=10.1
local operand2=20.2

result=$(echo ${operand1} ${operand2} | awk '{printf "%5.1f\n",$1/$2}') || exit 1

Increment an Integer

local i=0
((i++))

Decrement an Integer

local i=1
((i--))

Numeric Evaluation in a Condition

local a=1
local b=2
if [[ $(eval ${a} - ${b}) < 0 ]]; then
  ...
fi

Random Numbers

Bash script that generates a random MAC address