如何在 Bash 脚本中添加数字? [英] How can I add numbers in a Bash script?

查看:26
本文介绍了如何在 Bash 脚本中添加数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Bash 脚本,但我在第 16 行遇到了问题.如何获取第 15 行的先前结果并添加到第 16 行的变量?

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

推荐答案

对于整数:

num=$((num1 + num2))
num=$(($num1 + $num2))       # Also works
num=$((num1 + 2 + 3))        # ...
num=$[num1+num2]             # Old, deprecated arithmetic expression syntax

  • 使用外部 expr 实用程序.请注意,这仅适用于非常旧的系统.

  • Using the external expr utility. Note that this is only needed for really old systems.

    num=`expr $num1 + $num2`     # Whitespace for expr is important
    

  • 对于浮点:

    Bash 不直接支持这一点,但您可以使用一些外部工具:

    Bash doesn't directly support this, but there are 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
    

    您也可以使用科学记数法(例如,2.5e+2).

    You can also use scientific notation (for example, 2.5e+2).

    常见陷阱:

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

    • 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 (for example, num= or num)

    num=1 num =2

    bcexpr 期望每个数字和运算符作为单独的参数,因此空格很重要.他们不能处理像 3+ +4 这样的参数.

    bc and expr expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like 3+ +4.

    num=`expr $num1+ $num2`

    这篇关于如何在 Bash 脚本中添加数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆