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}
Try this:
#!/bin/bash
declare -A conect
for i in "$@"
do
echo $i
conect[$i]=0
done
echo ${#conect[@]}
Explanation:
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."$@"
is better than $*
, especially when (quoted) parameters may contain spaces. $* 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.
You should use an array:
for i in "$@"