0

when I check the length of the array is always 1 even I give more parameters in the command line

for i in $*
do 
echo $i
conect[$i]=0
done

echo ${#conect}
clausdia
  • 13
  • 4

3 Answers3

3

Try this:

#!/bin/bash
declare -A conect
for i in "$@"
do
    echo $i
    conect[$i]=0
done
echo ${#conect[@]}

Explanation:

  • An associative array (i.e. indexes can be non-numeric) must be declared with declare -A. You do not need this if indexes are guaranteed to be numeric.
  • ${#foo} is the length (number of characters) of a string-valued variable; ${#conect[@]} is the length (number of elements) of an array.
  • As pointed out by others, "$@" is better than $*, especially when (quoted) parameters may contain spaces.
Ruud Helderman
  • 10,563
  • 1
  • 26
  • 45
0

$* create one single argument separated with IFS. that's why. Use $@

What is the difference between "$@" and "$*" in Bash?

Edit Actually, as pointed out by @that_other_guy and @Ruud_Helderman (thanks to you both), what I said isn't quite right.

First thing is the Mea Culpa, as this matters isn't the full solution.

But it made me wonders so here is the correct way. The IFS difference is a fact. But this solely matters if you quote "$*" or "$@"

for i in "$*"
do
     echo $i
done

Will output every arguments on the same line whereas

for i in "$@"
do
     echo $i
done

Will do it one at a time.

Community
  • 1
  • 1
Kuu Aku
  • 320
  • 2
  • 6
  • `f() { for i in $*; do echo "Looping"; done; }; f 1 2 3` shows this to be false – that other guy Apr 24 '17 at 19:44
  • @KuuAku Excellent advice but not the reason for OP's problem; notice there were no quotes around `$*`. See the examples in this answer: http://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts#2761739 – Ruud Helderman Apr 24 '17 at 19:59
0

You should use an array:

for i in "$@"
Robert Seaman
  • 2,432
  • 15
  • 18
  • 1
    Excellent advice but not the reason for OP's problem; notice there were no quotes around `$*`. See the examples in this answer: http://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts#2761739 – Ruud Helderman Apr 24 '17 at 19:55