使用Bash 进行 数学运算
========================================================================
myself program and practice
Author: cjash
cjash@linux-h3i2:tmp\> echo $[8 + 3]
11
cjash@linux-h3i2:tmp\> echo $[8 | 3]
11
cjash@linux-h3i2:tmp\> echo $[8 | 7]
15
cjash@linux-h3i2:tmp\> echo $[8 | 12]
12
cjash@linux-h3i2:tmp\> echo $[0x08 | 0x88]
136
cjash@linux-h3i2:tmp\> echo $[0x08 | 0x0A]
10
cjash@linux-h3i2:tmp\> echo $[10 | 0x0A]
10
cjash@linux-h3i2:tmp\> AA=8
cjash@linux-h3i2:tmp\> echo $[AA | 0x0A]
10
cjash@linux-h3i2:tmp\> echo $[AA | 0x03]
11
cjash@linux-h3i2:tmp\> echo $[AA | 0b00000011]
bash: AA | 0b00000011: value too great for base (error token is "0b00000011")
cjash@linux-h3i2:tmp\> echo $AA
8
cjash@linux-h3i2:tmp\> echo $[ AA | 0x03 ]
11
== the application1 ==
do_operation=0
while :
do
case $1 in
-a)
do_operation=$[do_operation | 0x06]
;;
-k)
do_operation=$[do_operation | 0x02]
;;
-r)
do_operation=$[do_operation | 0x04]
;;
-i)
do_operation=$[do_operation | 0x08]
;;
-f)
do_operation=$[do_operation | 0x10]
;;
-u)
do_operation=$[do_operation | 0x20]
;;
-h)
do_operation=$[do_operation | 0x40]
;;
*)
break;
;;
esac
shift 1
done
printf "0x%x\n" ${do_operation}
if [ $[do_operation & 0x02 ] -ne 0 ]; then
echo "do kernel upgrade"
fi
if [ $[do_operation & 0x04 ] -ne 0 ]; then
echo "do filesystem upgrade"
fi
if [ $[do_operation & 0x08 ] -ne 0 ]; then
echo "ignore backup configure files"
fi
if [ $[do_operation & 0x10 ] -ne 0 ]; then
echo "-f appointed"
fi
if [ $[do_operation & 0x20 ] -ne 0 ]; then
echo "-u appointed"
fi
if [ $[do_operation & 0x40 ] -ne 0 ]; then
echo "-h appointed"
fi
== the application2 ==
do_operation=0
while :
do
case $1 in
-a)
do_operation=$((do_operation|0x06))
;;
-k)
do_operation=$((do_operation|0x02))
;;
-r)
do_operation=$((do_operation|0x04))
;;
-i)
do_operation=$((do_operation|0x08))
;;
-f)
do_operation=$((do_operation|0x10))
;;
-u)
do_operation=$((do_operation|0x20))
;;
-h)
do_operation=$((do_operation|0x40))
;;
*)
break;
;;
esac
shift 1
done
printf "0x%x\n" ${do_operation}
if [ $((do_operation&0x02)) -ne 0 ]; then
echo "do kernel upgrade"
fi
if [ $((do_operation&0x04)) -ne 0 ]; then
echo "do filesystem upgrade"
fi
if [ $((do_operation&0x08)) -ne 0 ]; then
echo "ignore backup configure files"
fi
if [ $((do_operation&0x10)) -ne 0 ]; then
echo "-f appointed"
fi
if [ $((do_operation&0x20)) -ne 0 ]; then
echo "-u appointed"
fi
if [ $((do_operation&0x40)) -ne 0 ]; then
echo "-h appointed"
fi
========================================================================
man information
ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and
declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no
check for overflow, though division by 0 is trapped and flagged as an error. The operators and their
precedence, associativity, and values are the same as in the C language. The following list of operators
is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing
precedence.
id++ id--
variable post-increment and post-decrement
++id --id
variable pre-increment and pre-decrement
- + unary minus and plus
! ~ logical and bitwise negation
** exponentiation
* / % multiplication, division, remainder
+ - addition, subtraction
<< >> left and right bitwise shifts
<= >= < >
comparison
== != equality and inequality
& bitwise AND
^ bitwise exclusive OR
| bitwise OR
&& logical AND
|| logical OR
expr?expr:expr
conditional operator
= *= /= %= += -= <<= >>= &= ^= |=
assignment
expr1 , expr2
comma
Shell variables are allowed as operands; parameter expansion is performed before the expression is evalu‐
ated. Within an expression, shell variables may also be referenced by name without using the parameter
expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without
using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression
when it is referenced, or when a variable which has been given the integer attribute using declare -i is
assigned a value. A null value evaluates to 0. A shell variable need not have its integer attribute
turned on to be used in an expression.
Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal.
Otherwise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing
the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. The
digits greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that
order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably
to represent numbers between 10 and 35.
Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and
may override the precedence rules above.
========================================================================
=====================================================================
from: http://wzgyantai.blogbus.com/logs/35896693.html
2009-03-01
Bash数学运算 - [Bash]
版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://wzgyantai.blogbus.com/logs/35896693.html使用bash也许有的时候会需要进行数学运算,如果想当然的声明两个变量,然后做数学
运算,结果会让人很意外的,需要使用declare -i命令来声明数字变量
下面是一个例子,运行一下就可以看到结果的差异了~~~
#!/bin/bash
#written by:flythought
#purpose:learn 'declare' in calculation
echo "now an example will be given for 'declare'";
var1=10;
var2=20;
echo "not use declare:"
echo $var1*$var2;
declare -i var3=10;
declare -i var4=20;
echo "when use declare:"
declare -i result=$var3*$var4;
echo $result;
做数学运算还可以用以下三种方法:
j=10
i=20
a=`echo $j + $i | bc -l`#方法1利用bc(-l选项表示使用数学库)
b=`expr $j + $i`#方法2利用内嵌命令expr
c=$(($j+$i))#方法3
printf "$a, $b, $c\n"
浮点运算与比较
默认情况下bash是不支持浮点运算和比较的,而是仅仅支持整形的,但是可以通过借助其他的程序来实现,其中上面的利用bc的方法1就可以进行浮点运算,
命令格式 echo "[选项];操作"|bc [选项],例如
echo "sacle=4;1/100"|bc #设置精度为小数点后面四位
echo "s(1)/c(1)"|bc -l #使用数学库计算tan(1)
那么如何利用bc进行浮点数的比较呢?
max=100.5
min=99.6
if [ $(echo "$max > $min"|bc) -eq 1 ]; then echo true
else
echo false
fi
解释:将一个逻辑判断式管道传给bc如果结果为真则返回1,否则返回0,这个和c一样,然后就可以利用这个结果进行进一步的操作了~~
此外还可以利用awk进行计算
echo `awk -v x=2.53 -v y=3.64 'BEGIN {printf "%.2f\n",x/y}'`
v=$(echo 123.45 123.44|awk '{ printf "%0.4f\n" ,$1/$2}')
比较也可以
echo 123.45 123.44 | awk '{if($1>$2) {printf"%f >%f\n",$1,$2} else {printf"%f <%f\n",$1,$2}}'
=====================================================================
from: %E5%9C%A8bash%E4%B8%AD%E8%BF%9B%E8%A1%8C%E6%95%B0%E5%AD%A6%E8%BF%90%E7%AE%97/
在BASH中进行数学运算
以前只知道expr,今天发现了BASH内置的let:
let: let arg [arg ...]
Each ARG is an arithmetic expression to be evaluated. Evaluation
is done in fixed-width integers with no check for overflow, though
division by 0 is trapped and flagged as an error. The following
list of operators is grouped into levels of equal-precedence operators.
The levels are listed in order of decreasing precedence.
id++, id– variable post-increment, post-decrement
++id, –id variable pre-increment, pre-decrement
-, + unary minus, plus
!, ~ logical and bitwise negation
** exponentiation
*, /, % multiplication, division, remainder
+, - addition, subtraction
<<, >> left and right bitwise shifts
<=, >=, <, > comparison
==, != equality, inequality
& bitwise AND
^ bitwise XOR
| bitwise OR
&& logical AND
|| logical OR
expr ? expr : expr
conditional operator
=, *=, /=, %=,
+=, -=, <<=, >>=,
&=, ^=, |= assignment
Shell variables are allowed as operands. The name of the variable
is replaced by its value (coerced to a fixed-width integer) within
an expression. The variable need not have its integer attribute
turned on to be used in an expression.
Operators are evaluated in order of precedence. Sub-expressions in
parentheses are evaluated first and may override the precedence
rules above.
If the last ARG evaluates to 0, let returns 1; 0 is returned
otherwise.
注:是“脚本”,不是“角本”。
2008-07-02
今天又有新的发现:
(( … )): (( expression ))
The EXPRESSION is evaluated according to the rules for arithmetic
evaluation. Equivalent to “let EXPRESSION”.
$a=1
$(( a++ ))
$echo $a
2
=====================================================================
from:
shell中的数学运算
关键词: csh shell bc
一般整数表达试可以用:
set x = `expr 3 - 2`
但如果其中有小数时就不行了,这个时候就要用到bc
echo "3 - 1.5"|bc
echo 10/3 | bc -l
3.33333333333333333333
还可以控制输出精度:
echo "scale=2;10/3"|bc
输出3.33
ibase=2 表示二进制运算
除了bc外还有dc,不过语法相对较复杂
当然还可以用awk,perl来实现:
awk 'BEGIN{print 2+0.5}'
perl -e "printf 2+3"
echo $((1+1)),BASH支持,但是如果有小数参与运算就不支持了
=====================================================================
如何用shell bash做數學運算
echo `($re3+$re4)/$re*100`%
echo `$re3/($re3+$re4)*100`%
echo `$re4/($re3+$re4)*100`%
我這樣寫了shell但是總是抱錯,到底怎麼樣才能用變量做數學運算。多謝指教
bc,awk,均可,shell只能處理整數(據說bash3可以處理浮點數,沒實驗過)
能告訴我如何用awk實現嗎?$re4$re3等等都是前面的變量,我不知道如何在awk裡面繼續用那些變量
-->
ex:
[code]
awk -v a=123 -v b=456 'BEGIN{printf "%d %d %d %.2f\n",a+b,a-b,a*b,a/b}'[/code]
BTW:更多awk用法,搜索論壇精華區
-->
希望下面的例子對你有幫助:)
a=5
b=6
echo $[$a + $b]
或
echo `expr $a + $b`
bash不太清楚,我總是用csh
我一般這樣:
echo "scale=5;$a+$b"|bc
=====================================================================
from:
bash下. : () {} [] [[]] (())的解释
bash下有很多像{}、[]等一些符号命令,下面是我对一些常用的符号命令的学习笔记,若有错误或纰漏望各位兄弟指正。
一、.(source)
.(点)与source命令一样,从文件中读取并执行命令,无论该文件是否都有可执行权限都能够正确的执行。且是在当前shell下执行,而不是产生一个子shell来执行(我们通常使用“./filename.sh”去执行一个文件是在当前shell下产生一个子shell去执行的)。所以在设置bash的环境的变量时,就必须用该命令或者source命令去执行设置的环境变量才会对当前shell生效,如下:
fori in/etc/profile.d/*.sh do
if[-r "$i"]then
.$i
fi
done
二、:
: 该命令什么都不做,但执行后会返回一个正确的退出代码,即exit 0。比如在if语句中,then后面不想做任何操作,但是又不能空着,这时就可以使用“:”来解决,如下:
if["$i"-ne1 ]then
:
else
echo"$i is not equal 1"
fi
三、()
() 将多个命令组合在一起执行,相当于一个命令组。
四、{}
{} 和()类似,也是将多个命令组合在一起。它们之间的区别是,()是在产生的子shell下执行,而{}是在当前的shell下执行。这与前面讲到是使用". filename.sh"和"./filename.sh"的区别一样。举一个很简单的例子:
# A=123# (A=abcecho$A)echo$A
abc
123#{ A=abcecho$A}echo$A
abc
abc
从上面的示例可以看出,当在()中赋值的变量,影响的只是自身的子shell,而不能将该值赋给父shell,因为“父亲不能继承儿子”。而在{}中赋值的变量,因为就在当前的shell执行的,所以就能改变原来变量的值。
注意:()里面两边可以不使用空格,{}里面两边必须使用空格,且最后一个命令也需要以“;”结尾,表示命令结束。
五、[](test)
[] 与test命令一样,用于比较值以及检查文件类型。如下:
1、[ "$A" = 123 ]:是字符串的测试,以测试 $A 是否为 1、2、3 这三个连续的"文字"。
2、[ "$A" -eq 123 ]:是整数的测试,以测试 $A 是否等于"一百二十三"。
3、[ -e "$A" ]:是关于文件的测试,以测试 123 这份"文件"是否存在。
六、[[]]
[[]]可以说是[]的“增强版”,它能够将多个test命令支持的测试组合起来,例如:
# [[ (-d "$HOME") &&(-w "$HOME") ]] &&echo echo "home is a writable directory"
home is a writable directory
至于这两者的区别有位仁兄已经写的很清楚了,我将其整理一下:
数字测试: -eq-ne-lt-le-gt-ge,[[]]同 []一致
文件测试: -r、-l、-w、-x、-f、-d、-s、-nt、-ot,[[]]同 []一致
字符串测试: ><=(同==)!=-n -z,不可使用“<=”和“>=”,[[]]同 []一致,但在[]中,>和<必须使用\进行转义,即\>和\<
逻辑测试: []为 -a -o ![[]]为&& ||!
数学运算: []不可以使用 [[]]可以使用+-*/ %
组合: 均可用各自逻辑符号连接的数字(运算)测试、文件测试、字符测试
拿这两者对字符串的测试举一个例子,如下:
# [a \>1 ]&&echoture ||echofalse
ture
# [[a >1 ]]&&echoture ||echofalse
ture
字符串的比较是根据相应的ASCII码来比较的,所以a>1是成立的。如果有兴趣也可以思考一下为什么会出现下面的结果?
# [[a >1 ]]&&echoture ||echofalse
ture
七、(())
(())专门来做数值运算,如果表达式求值为 0,则设置退出状态为 1;如果求值为非 0 值,则设置为 0。不需要对 ((和 ))之间的操作符转义。算术只对整数进行。除 0 会产生错误,但不会产生溢出。可以执行 C 语言中常见的算术、逻辑和位操作。如下:
# ((i=1+99))echo$i
100
也能:
# i=99((i++))echo$i
100
除此之外,也可以使用$(())直接进行数值运算,如下:
# echo$((2**3))
8
注意:使用 (( )) 时,不需要空格分隔各值和运算符,使用[]和[[ ]] 时需要用空格分隔各值和运算符。