755

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick
  • 7,567
  • 3
  • 15
  • 4
  • 2
    I think you will print a zero value even using following answer. There's a trick, e.g. process substition, to bring the final value of "inside num" to "outside num". – Scott Chu Feb 13 '15 at 06:45

13 Answers13

1270

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 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

You can also use scientific notation (for example, 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 (for example, num= or num)

    num= 1 num =2

  • 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`

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • 1
    In the first answer it prints me expr:non-numeric argument The second doesn't work.. – Nick Jun 14 '11 at 19:35
  • 1
    @Nick: Did you try this while variables named `num1` and `num2` existed and had integer values? – sorpigal Jun 14 '11 at 20:20
  • 1
    Yew they are existed but the one variable is double.. is that a problem?? – Nick Jun 14 '11 at 20:35
  • 2
    Yeah, that's a problem :) Note: the `$((..))` arithmetic evaluation is executed in bash. `expr` is executed as a separate process, so it's going to be a lot slower. use the latter one on systems where the arithemtic evaluation isn't supported (sh!=bash) – Karoly Horvath Jun 14 '11 at 21:52
  • 4
    Since `$((…))` is standardized by POSIX, it should become increasingly rare that `expr` is necessary. – chepner Oct 28 '13 at 20:50
  • I am thinking your answer here for local variables http://unix.stackexchange.com/q/229049/16920 – Léo Léopold Hertz 준영 Sep 11 '15 at 13:00
  • Any issues with a function like this in your profile? function calc() { echo "${1}" | bc -l; } callable as calc '1 + 2' or calc '1 / 2'. originally I was going with $((...)) but it does not handle floating point. – jatal Feb 04 '17 at 02:07
  • `expr` POSIX documentation itself recommends to use $(()) instead in new scripts: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html — – Dereckson Oct 30 '17 at 13:58
  • @KarolyHorvath I'm trying to use my integer `$num` (which equals 13 in this example), as computed in the first example, in a for loop ```for i in {$numDays..1}```, but I get ```{13..1}: integer expression expected```. Why isn't `$num` an integer? – AstroFloyd Apr 03 '20 at 14:41
179

Use the $(( )) arithmetic expansion.

num=$(( $num + $metab ))

See Chapter 13. Arithmetic Expansion for more information.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Steve Prentice
  • 23,230
  • 11
  • 54
  • 55
36

There are a thousand and one ways to do it. Here's one using dc (a reverse Polish desk calculator which supports unlimited precision arithmetic):

dc <<<"$num1 $num2 + p"

But if that's too bash-y for you (or portability matters) you could say

echo $num1 $num2 + p | dc

But maybe you're one of those people who thinks RPN is icky and weird; don't worry! bc is here for you:

bc <<< "$num1 + $num2"
echo $num1 + $num2 | bc

That said, there are some unrelated improvements you could be making to your script:

#!/bin/bash

num=0
metab=0

for ((i=1; i<=2; i++)); do
    for j in output-$i-* ; do # 'for' can glob directly, no need to ls
            echo "$j"

             # 'grep' can read files, no need to use 'cat'
            metab=$(grep EndBuffer "$j" | awk '{sum+=$2} END { print sum/120}')
            num=$(( $num + $metab ))
    done
    echo "$num"
done

As described in Bash FAQ 022, Bash does not natively support floating point numbers. If you need to sum floating point numbers the use of an external tool (like bc or dc) is required.

In this case the solution would be

num=$(dc <<<"$num $metab + p")

To add accumulate possibly-floating-point numbers into num.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sorpigal
  • 25,504
  • 8
  • 57
  • 75
  • 1
    @Sorpigal Thankssss a lot.. Can i ask you something else..how can i print at the end not the num but the num/10 ?? – Nick Jun 14 '11 at 21:03
27

I always forget the syntax so I come to Google Search, but then I never find the one I'm familiar with :P. This is the cleanest to me and more true to what I'd expect in other languages.

i=0
((i++))

echo $i;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ssshake
  • 279
  • 3
  • 2
27

In Bash,

 num=5
 x=6
 (( num += x ))
 echo $num   # ==> 11

Note that Bash can only handle integer arithmetic, so if your AWK command returns a fraction, then you'll want to redesign: here's your code rewritten a bit to do all math in AWK.

num=0
for ((i=1; i<=2; i++)); do
    for j in output-$i-*; do
        echo "$j"
        num=$(
           awk -v n="$num" '
               /EndBuffer/ {sum += $2}
               END {print n + (sum/120)}
           ' "$j"
        )
    done
    echo "$num"
done
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
20

I really like this method as well. There is less clutter:

count=$[count+1]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
unixball
  • 209
  • 2
  • 2
18
 #!/bin/bash
read X
read Y
echo "$(($X+$Y))"
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Amarjeet Singh
  • 181
  • 1
  • 2
11

You should declare metab as integer and then use arithmetic evaluation

declare -i metab num
...
num+=metab
...

For more information, see 6.5 Shell Arithmetic.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pavel
  • 182
  • 1
  • 9
11

Use the shell built-in let. It is similar to (( expr )):

A=1
B=1
let "C = $A + $B"
echo $C # C == 2

Source: Bash let builtin command

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
charles
  • 263
  • 5
  • 7
7

Another portable POSIX compliant way to do in Bash, which can be defined as a function in .bashrc for all the arithmetic operators of convenience.

addNumbers () {
    local IFS='+'
    printf "%s\n" "$(( $* ))"
}

and just call it in command-line as,

addNumbers 1 2 3 4 5 100
115

The idea is to use the Input-Field-Separator(IFS), a special variable in Bash used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +.

Remember the IFS is changed locally and does not take effect on the default IFS behaviour outside the function scope. An excerpt from the man bash page,

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.

The "$(( $* ))" represents the list of arguments passed to be split by + and later the sum value is output using the printf function. The function can be extended to add scope for other arithmetic operations also.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Inian
  • 80,270
  • 14
  • 142
  • 161
6
#!/usr/bin/bash

#integer numbers
#===============#

num1=30
num2=5

echo $(( num1 + num2 ))
echo $(( num1-num2 ))
echo $(( num1*num2 ))
echo $(( num1/num2 ))
echo $(( num1%num2 ))

read -p "Enter first number : " a
read -p "Enter second number : " b
# we can store the result
result=$(( a+b ))
echo sum of $a \& $b is $result # \ is used to espace &


#decimal numbers
#bash only support integers so we have to delegate to a tool such as bc
#==============#

num2=3.4
num1=534.3

echo $num1+$num2 | bc
echo $num1-$num2 | bc
echo $num1*$num2 |bc
echo "scale=20;$num1/$num2" | bc
echo $num1%$num2 | bc

# we can store the result
#result=$( ( echo $num1+$num2 ) | bc )
result=$( echo $num1+$num2 | bc )
echo result is $result

##Bonus##
#Calling built in methods of bc 

num=27

echo "scale=2;sqrt($num)" | bc -l # bc provides support for calculating square root

echo "scale=2;$num^3" | bc -l # calculate power
Udesh
  • 2,415
  • 2
  • 22
  • 32
4
#!/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)
        let num=num+metab (line 16)
    done
    echo "$num"
done
Stephen Newell
  • 7,330
  • 1
  • 24
  • 28
-1

Works on MacOS. bc is a command line calculator

#!/bin/bash

sum=0
for (( i=1; i<=5; i++ )); do
    sum=$(echo "$sum + 1.1" | bc) # bc: if you want to use decimal
done
echo "Total: $sum"
Ericgit
  • 6,089
  • 2
  • 42
  • 53