Home > Software engineering >  Why does "echo $array" print all members of the array in this specific case instead of onl
Why does "echo $array" print all members of the array in this specific case instead of onl

Time:09-23

I have encountered a very curious problem, while trying to learn bash.

Usually trying to print an echo by simply parsing the variable name like this only outputs the first member Hello.

#!/bin/bash

declare -a test

test[0]="Hello"
test[1]="World"

echo $test # Only prints "Hello"

BUT, for some reason this piece of code prints out ALL members of the given array.

#!/bin/bash

declare -a files
counter=0

for file in "./*"
do
    files[$counter]=$file
    let $((counter  ))
done

echo $files # prints "./file1 ./file2 ./file3" and so on

And I can't seem to wrap my head around it on why it outputs the whole array instead of only the first member. I think it has something to do with my usage of the foreach-loop, but I was unable to find any concrete answer. It's driving me crazy!

Please send help!

CodePudding user response:

When you quoted the pattern, you only created a single entry in your array:

$ declare -p files
declare -a files=([0]="./*")

If you had quoted the parameter expansion, you would see

$ echo "$files"
./*

Without the quotes, the expansion is subject to pathname generation, so echo receives multiple arguments, each of which is printed.

To build the array you expected, drop the quotes around the pattern. The results of pathname generation are not subject to further word-splitting (or recursive pathname generation), so no quotes would be needed.

for file in ./*
do
   ...
done
  • Related