Reputation: 1170
Why does this bash script (at bottom) not output the newline? The result is:
filesonetwothree
instead of
files
one
two
three
Here's the script:
files=()
files+="one"
files+="two"
files+="three"
printf "\nfiles"
for file in "${files[@]}"
do
printf "$file\n"
done
NOTE: This is on a Mac running macOS Sierra
Upvotes: 0
Views: 179
Reputation: 295736
The following will make your issue very clear:
files=()
files+="one"
files+="two"
files+="three"
declare -p files
...emits as output:
declare -a files='([0]="onetwothree")'
...so, you were appending to the first element of the array, not adding new elements to the array's end.
To correctly append to an array, use the following instead:
files=()
files+=("one")
files+=("two")
files+=("three")
declare -p files
...which emits:
declare -a files='([0]="one" [1]="two" [2]="three")'
In either case, to print your array one-line-to-an-element, use a format string with a newline, and pass your array elements as subsequent arguments:
printf '%s\n' "${files[@]}"
Upvotes: 4