Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

#!/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 
like image 564
Nick Avatar asked Jun 14 '11 19:06

Nick


People also ask

Can bash variables have numbers?

Legal Rules of Naming Variables in Bash Don't use spaces after the initialization of the variable name and its value. A variable name can have letter/s. A variable name can have numbers, underscores, and digits.

How do I declare a numeric variable in bash?

#!/bin/bash func1 () { echo This is a function. } declare -f # Lists the function above. echo declare -i var1 # var1 is an integer. var1=2367 echo "var1 declared as $var1" var1=var1+1 # Integer declaration eliminates the need for 'let'.


1 Answers

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`

like image 125
Karoly Horvath Avatar answered Oct 09 '22 00:10

Karoly Horvath