converting string to number in shell script

Hi,

I am having a problem in converting a string to number so I can preform arithmetic operations.

timeTot=0
timeTmp=$(cat idsOutput | grep 'Run time' | cut -c 36-39)
timeTot=$[$timeTot+$timeTmp] #This is line 28
echo "total RunTime=" $timeTot

this is the error msg:

./ids2.sh: line 28: 0+1.35: syntax error: invalid arithmetic operator (error token is ".35")
total RunTime= 0

Please post the output of cat idsOutput | grep 'Run time'

cat idsOutput

Commencing packet processing (pid=2103)

Run time for packet processing was 1.3579 seconds

#!/bin/bash
timeTot=0
timeTmp=$(grep 'Run time' input | cut -c36-39)
timeTot=`echo "$timeTot + $timeTmp" | bc`
echo "total RunTime=" $timeTot
$ echo "0 + `awk '/Run time/ {print $7}' idsOutput`" | bc
1.3579
$ echo "10 + `awk '/Run time/ {print $7}' idsOutput`" | bc
11.3579

Try .. in your script ..

timeTot=`echo "$timeTot + $timeTmp" | bc`; echo "total RunTime=" $timeTot

--Shirish Shukla

Thank you balajesuri
it works

However, I am doing this code inside a loop and then taking the average (avgT).
but the output of avgT is the integer part of the solution
I tried to use the bc method for the average but it only giving me the integer part of the solution.

Here is my code:

#!/bin/bash
myLoop=$1
i=1
timeTot=0

while [ $i -le $myLoop ]
do
timeTmp=$(grep 'Run time' input | cut -c36-39)
timeTot=`echo "$timeTot + $timeTmp" | bc`
i=$[$i+1]
done

echo "total RunTime=" $timeTot
avgT=`echo "$timeTot / $myLoop" | bc`
echo "Average RunTime=" $avgT

the output

./ids2.sh 2
total RunTime= 2.85
Average RunTime= 1

the value of Average RunTime should be = 2.85/2 = 1.425

use scale=3

$ echo "scale=3; 2.85 / 2" | bc
1.425

It works :slight_smile:

many thanks to you itkamaraj

many thanks to all of you guys