bash arithmetic expressions with variables

前端 未结 2 722
孤城傲影
孤城傲影 2020-12-21 22:25

I am having troubles with the arithmetic expressions in a bash file (a unix file .sh).

I have the variable \"total\", which consists of a few numbers separated by sp

相关标签:
2条回答
  • 2020-12-21 23:20

    There are a number of ways to perform arithmetic in Bash. Some of them are:

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

    You may see more on the wiki. If you need to handle non-integer values, use a external tool such as bc.

    0 讨论(0)
  • 2020-12-21 23:21

    Wrap arithmetic operations within ((...)):

    dollar=0
    for a in $total; do
      ((dollar += a))
    done
    
    0 讨论(0)
提交回复
热议问题