4

I'm trying to write a simple bash script that adds integers and supplies the sum. I figured the easiest way would be to assign the input to an array. Then traverse the array to perform the summation. I need to use the length of the array in my for loop and cannot figure out how to assign the array length to a variable.

Any help appreciated on the simple script (which I did to learn bash)

#!/bin/bash
# add1 : adding user supplied ints

echo -n "Please enter any number of integers: "
read -a input

echo "Your input is ${input[*]}"
echo "${#input[@]} number of elements"

num = ${#input[@]}   # causing error
for ((i = 0; i < "${num}"; ++i )); do  # causing error
  sum = $((sum + input[$i]))
done

echo "The sum of your input is $sum"

Which yields the errors:

line 10: num: command not found 
line 11: ((: i < :syntax error: operand expected (error token is "< ")
4
  • 1
    Here is more information on assignment conventions in Bash :) Commented May 1, 2013 at 18:10
  • You say "causing error"; it would be helpful to know what error it is causing. Commented May 1, 2013 at 18:16
  • @msw - Already solved. Thanks for the feedback. The error was: line 10: num: command not found line 11: ((: i < : syntax error: operand expected (error token is "< ") Commented May 1, 2013 at 18:37
  • In the future, you should include (or edit) that into your question. Commented May 1, 2013 at 18:39

1 Answer 1

10

You just have a syntax error. Remove the space before =:

num = ${#input[@]}   # causing error

becomes:

num=${#input[@]}   # works

Note that if you assign to a variable in bash using the = operator, there MUST NOT be any space before and after the =

Read this entry about Variable Assignment in the Advanced Bash-Scripting Guide

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It works. I had the same error throughout the program. And I feel like an idiot. Coming from C++ where that space doesn't matter...
don't worry about that. every bash coder has once seen this error ;)

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.