stackoverflower
stackoverflower

Reputation: 565

What is the right bash syntax to add two numbers from string array?

I have to read a string from pipe, and I am using

read -a line 

for that.

And then I need to calculate two numbers from the string (the string contains numbers at this point exactly at the places I need).

And then I am trying to write this:

number= 10*${line[4]} + ${line[5]}

and getting these errors from bash:

local: `10*1': not a valid identifier
local: `+': not a valid identifier

How to write it correctly that those string fields will be converted to numbers ("50" to 50 etc.) and participate in expression?

Upvotes: 2

Views: 2019

Answers (3)

James
James

Reputation: 4737

Another way to evaluate expressions:

result=$(expr "1" + "2")
echo $result #=> 3

See the expr man page:

man expr

Upvotes: 1

michas
michas

Reputation: 26555

a=(2 3 4)
let sum=${a[0]}+${a[1]}+${a[2]}
echo $sum

Upvotes: 2

fedorqui
fedorqui

Reputation: 290135

Let's see an example:

$ a[0]=12
$ a[1]=23
$ res=$(( ${a[0]} + ${a[1]}))
$ echo $res
35

So in your case you need to do

num=$(( 10*${line[4]} + ${line[5]}))

Upvotes: 5

Related Questions