Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign array length to a variable in bash

Tags:

bash

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 "< ")
like image 656
Dorian Avatar asked Oct 21 '25 18:10

Dorian


1 Answers

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

like image 65
hek2mgl Avatar answered Oct 25 '25 02:10

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!