Yong Li
Yong Li

Reputation: 647

What does # mean in front of an array name in bash script?

I read such a line:

arrayA=$((${#arrayB[@]}+${#arrayC[@]}));

What does it do? Especially what's the meaning of # in front of array name?

Upvotes: 1

Views: 373

Answers (2)

Olli K
Olli K

Reputation: 1760

The line:

arrayA=$((${#arrayB[@]}+${#arrayC[@]}));

Reads: set the value of variable arrayA as the summed length of arrayB and arrayC

$(()) is the arithmetic expansion syntax in which you have the sum + of the two array lengths ${#array[@]}

Upvotes: 1

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

${#a[@]} expands to the number of elements in the array a. See the Shell Parameter Expansion section of the reference manual.

Thanks @gniourf_gniourf, but what is this line does in overall? I tried to run the rhs in my terminal with two arrays, and it seems to try to execute the sum result as a command? This doesn't make sense to me...

  • $((...)) is the arithmetic context.
  • ${#arrayB[@]} and ${#arrayC[@]} expand to the number of elements in arrayB and arrayC respectively.
  • Hence $((${#arrayB[@]}+${#arrayC[@]})) expands to the sum of the number of elements in arrayB and arrayC. Check it with echo $((${#arrayB[@]}+${#arrayC[@]})).
  • Hence your snippet will assign to the variable arrayA the sum of the number of elements in arrayB and arrayC.

Demo:

$ arrayB=( one two three )
$ arrayC=( alpha beta gamma delta )
$ echo "${#arrayB[@]}"
3
$ echo "${#arrayC[@]}"
4
$ echo "$(( ${#arrayB[@]} + ${#arrayC[@]} ))"
7
$ arrayA=$(( ${#arrayB[@]} + ${#arrayC[@]} ))
$ echo "$arrayA"
7

Upvotes: 5

Related Questions