Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash array using @ vs *, difference between the two

Tags:

linux

bash

I cannot pinpoint the exact difference between using ${array[@]} vs ${array[*]}

What diff I see is when printing, but I guess there is more to it

declare -a array
array=("1" "2" "3")
IFS=","
printf "%s" ${array[@]}
printf "%s" ${array[*]}
IFS=" "

I searched on TLDP about it, but couldn't figure it out. Is it a general bash thing or just for arrays? Thanks a lot!

like image 376
Dimitrie Mititelu Avatar asked Oct 01 '18 11:10

Dimitrie Mititelu


People also ask

What does %% mean in bash?

The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching.

What is the difference between and [[ in bash?

(difference) [[ is a keyword. ​ [[ is a shell keyword (invoke type [[ in Bash to confirm this). Like the [ builtin, the [[ keyword belongs to Bash; but it does not behave like a command. (similarity) [[ requires a space after.


1 Answers

As mentioned in man bash:

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 separate word.

Examples:

array=("1" "2" "3")
printf "'%s'" "${array[*]}"
'1 2 3'
printf "'%s'" "${array[@]}"
'1''2''3'
like image 183
oliv Avatar answered Oct 11 '22 00:10

oliv