Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

bash - 如何在bash脚本中添加数字(How can I add numbers in a bash script)

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?

(我有这个bash脚本,我在第16行遇到了问题。如何获取第15行的先前结果并将其添加到第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
  ask by Nick translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For integers :

(对于整数 :)

  • Use arithmetic expansion : $((EXPR))

    (使用算术扩展$((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.

    (使用外部expr实用程序。)

    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:

(Bash并不直接支持这一点,但您可以使用几种外部工具:)

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 (eg: 2.5e+2 )

(您也可以使用科学记数法(例如: 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= or num )

    (设置变量时,你不能在=两边都有空格,否则会强制shell将第一个单词解释为要运行的应用程序的名称(例如: num=num ))

    num= 1 num =2

    ( num= 1 num =2 )

  • bc and expr expect each number and operator as a separate argument, so whitespace is important.

    (bcexpr期望每个数字和运算符作为单独的参数,因此空格很重要。)

    They cannot process arguments like 3+ +4 .

    (他们无法处理像3+ +4这样的论点。)

    num=`expr $num1+ $num2`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...