2

I have an array

snapshots=(1 2 3 4)

When I run

printf "${snapshots[*]}\n"

It prints as expected

1 2 3 4

But when I run

printf "${snapshots[@]}\n"

It just prints

1

without a newline. My understanding is that accessing an array with @ is supposed to expand the array so each element is on a newline but it does not appear to do this with printf while it does do this with echo. Why is this?

0

1 Answer 1

7

printf interprets its first argument as a format string, and prints that; any further arguments are only used as required in the format string.

With printf "${snapshots[*]}\n", the first argument is the elements of the array joined with the first character of $IFS (space by default) followed by backslash and n: "1 2 3 4\n". Printing that shows all the values in the array separated by spaces and followed by a newline.

With printf "${snapshots[@]}\n", the first argument is the first entry in the array, "1", and the rest of the array is provided as separate arguments for the format string to use. The last argument has \n appended: "2" "3" "4\n". Since the format string doesn’t reference any additional arguments, they are all ignored. All that is output is the first value, with no following newline.

To see all the values when using @, you need to provide an actual format string:

printf "%s\n" "${snapshots[@]}"

A format string containing a reference to arguments is repeated as many times as necessary to consume all the arguments. So a single reference is sufficient to print all the values in the array, here with each followed by a newline character.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.