2

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?

1
  • bash hack to get number is smth like $((var+0)) Commented May 30, 2013 at 19:01

3 Answers 3

5

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]}))
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

In this context, you'll have to be careful to escape multiplication so the * does not expand into filenames
1

Another way to evaluate expressions:

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

See the expr man page:

man expr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.