我怎么能在bash脚本添加号码 [英] How can I add numbers in a bash script
问题描述
我有这样的bash脚本,我不得不在第16行的一个问题。
我怎么能走行15 $ P $ pvious结果,并添加
它在第16行的变量
#!/斌/庆典NUM = 0
代谢= 0为((i = 1; I< = 2;我++));做
在`LS输出 - $ I-Ĵ*`;做
回声$ J 代谢= $(猫附加$ J | grep的EndBuffer | awk的'{总和+ = $ 2} END {打印总和/ 120}')(line15)
NUM = $ NUM + $代谢(line16)
DONE
回声$ NUM
DONE
的对于整数的:
-
使用算术扩展:
$((表达式))
NUM = $((NUM1 + NUM2))
NUM = $(($ NUM1 + NUM2 $))#也适用
NUM = $((NUM1 + 2 + 3))#...
NUM = $ [NUM1 + NUM2]#老,德precated算术EX pression语法 -
使用外部
EXPR
工具。请注意,这只是需要真的老系统。NUM =`$ EXPR NUM1 + $#num2`为EXPR空白是非常重要的
的对于浮点的:
击不直接支持这一点,但有一对夫妇的外部工具可以使用:
NUM = $(awk的BEGIN {$打印NUM1 + NUM2 $;出口})
NUM = $(蟒蛇-c打印$ NUM1 + NUM2 $)
NUM = $(perl的-e打印$ NUM1 + NUM2 $)
NUM = $(回声$ NUM1 + NUM2 $ | BC)回波#空格是非常重要的
您也可以用科学记数法(例如: 2.5E + 2
)
的常见的问题的:
-
在设置变量,你不能有空格的
=
的两侧,否则将强制外壳间preT的第一个字为运行该应用程序的名称(例如:NUM =
或NUM
)<击>
NUM = 1
罢工> <击>NUM = 2
击> -
BC
和EXPR
期望每个号码和运营商作为一个单独的参数,因此空格是很重要的。他们不能像处理参数3 +
+4
。<击>
NUM =`$ EXPR NUM1 + $ num2`
击>
I have this bash script and I had a problem in line 16. How can I take the previous result of line 15 and add it to the variable in line 16?
#!/bin/bash
num=0
metab=0
for ((i=1; i<=2; i++)); do
for j in `ls output-$i-*`; do
echo "$j"
metab=$(cat $j|grep EndBuffer|awk '{sum+=$2} END { print sum/120}') (line15)
num= $num + $metab (line16)
done
echo "$num"
done
For integers:
Use arithmetic expansion:
$((EXPR))
num=$((num1 + num2)) num=$(($num1 + $num2)) # also works num=$((num1 + 2 + 3)) # ... num=$[num1+num2] # old, deprecated arithmetic expression syntax
Using the external
expr
utility. Note that this is only needed for really old systems.num=`expr $num1 + $num2` # whitespace for expr is important
For floating point:
Bash doesn't directly support this, but there's a couple of external tools you can use:
num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc) # whitespace for echo is important
You can also use scientific notation (e.g.: 2.5e+2
)
Common pitfalls:
When setting a variable, you cannot have whitespace on either side of
=
, otherwise it will force the shell to interpret the first word as the name of the application to run (eg:num=
ornum
)num= 1
num =2
bc
andexpr
expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like3+
+4
.num=`expr $num1+ $num2`
这篇关于我怎么能在bash脚本添加号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!