Shell plastic calculation floating point operation

Plastic calculation

1.$((num1+num2))

[shuqiq@shuqiq mybash]$ echo $((1+2))
3
[shuqiq@shuqiq mybash]$ echo $((1*2))
2

2.$[num1+num2]

[shuqiq@shuqiq mybash]$ echo $[1+2]
3
[shuqiq@shuqiq mybash]$ echo $[1*2]
2

3.expr num1 + num2

[shuqiq@shuqiq mybash]$ expr 1 + 1
2
[shuqiq@shuqiq mybash]$ expr 1 * 1
expr: 语法错误
[shuqiq@shuqiq mybash]$ expr 1 \* 1
1
[shuqiq@shuqiq mybash]$ 

4. let command: Like the double parentheses (( )), the let command can only perform integer operations, and cannot perform operations on decimals (floating point numbers) or strings.

let b=$b+1
echo $b

 Note: Forlet x+ywriting like this, although the shell calculates the value of x+y, it discards the result; if you don’t want this, you can use the method tolet sum=x+ysave the result of x+y in the variable sum.

let b=$1+$2
echo $b

plastic comparison

1.((num1=num2))

if (($1>$2))
then 
echo "1"
else echo "0"
fi

2.test num1 -eq num2

Parameters of the test command:

"-eq" = "="    "-ne" = "!="
"-lt" = "<"     "-le" = "<="
"-gt" = ">"     "-ge" = ">="

if test $1 -eq $2
then
echo '1'
else echo '0'
fi

3.[num1 -eq num2]

if [  $1 -eq $2 ] 
then
echo '1'
else echo '0'
fi

floating point calculation

Floating point calculations require a bc calculator

install bc calculator

yum -y install bc

calculate

"salce=1;num1+num2" | bc
#salce:保留几位小数

Floating point comparison

Floating point comparison also needs to use bc calculator

if [ $(echo "$a>=$b" | bc) -eq 1 ]
then 
echo '1'
else echo '0'
fi
####或者下面这几种
if [ `echo "$a>=$b" | bc` -eq 1 ]
then
echo '1'
else echo '0'
fi
#
if ((`echo "$a>=$b" | bc` == 1))
then
echo '1'
else echo '0'
fi
#
if test `echo "$a>=$b" | bc` -eq 1 
then
echo '1'
else echo '0'
fi

Guess you like

Origin blog.csdn.net/qq_53368181/article/details/130057330