【问题标题】:bash arithmetic expressions with variables带有变量的 bash 算术表达式
【发布时间】:2023-03-20 09:23:01
【问题描述】:

我在使用 bash 文件(unix 文件 .sh)中的算术表达式时遇到问题。

我有变量“total”,它由几个用空格分隔的数字组成,我想计算它们的总和(在变量“dollar”中)。

#!/bin/bash
..
dollar=0
for a in $total; do
  $dollar+=$a
done

我知道我在算术括号中遗漏了一些东西,但我无法让它与变量一起使用。

【问题讨论】:

标签: bash arithmetic-expressions


【解决方案1】:

((...)) 中封装算术运算:

dollar=0
for a in $total; do
  ((dollar += a))
done

【讨论】:

    【解决方案2】:

    在 Bash 中有多种方法可以执行算术运算。其中一些是:

    dollar=$(expr $dollar + $a)
    let "dollar += $a"
    dollar=$((dollar + a))
    ((dollar += a))
    

    您可能会在the wiki 上看到更多信息。如果您需要处理非整数值,请使用外部工具,例如 bc

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      相关资源
      最近更新 更多