0

what is the "@" meaning, code:

#!/bin/bash array[0]=1 array[1]=2 array[2]=3 array[3]=4 array[4]=5 #work for num in ${array[@]} do echo $num done #not work for num in array do echo $num done 

In the loop, why use ${array[@]} not $array, thx

3 Answers 3

1

This is the syntax defined by the language. This is just how it works. Read about it in man bash, search for the section titled "Arrays". Here's the relevant part:

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or * , the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a sep‐ arate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters * and @ (see Special Parameters above).

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

Comments

0

$array doesn't work like an array. It more nearly acts like ${array[0]}.

Comments

0

$array evaluates to the first element in the array. You must use ${array[@]} (or more properly, "${array[@]}") to indicate each element of the array in turn, separated by the first character of $IFS.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.