-1

There are some files in my work directory like below:

20191101.data.lz4
20191104.data.lz4
20191105.data.lz4
20191106.data.lz4
20191107.data.lz4
20191108.data.lz4
20191111.data.lz4
20191112.data.lz4
20191113.data.lz4
20191114.data.lz4
20191115.data.lz4
20191118.data.lz4
20191119.data.lz4

Now I need to process these files. If I use below command defin a array the for loop work as my expect, print all file in my work directory.

FILE_LIST=$(ls /my/work/dir)
for EACH_FILE in ${FILE_LIST}
do
    echo $EACH_FILE
done

But if I defin array as below, the for loop only print the first element of array.

FILE_LIST=(20191101.data.lz4
20191104.data.lz4
20191105.data.lz4
20191106.data.lz4
20191107.data.lz4
20191108.data.lz4
20191111.data.lz4
20191112.data.lz4
20191113.data.lz4
20191114.data.lz4
20191115.data.lz4
20191118.data.lz4
20191119.data.lz4)
for EACH_FILE in ${FILE_LIST}
do
    echo $EACH_FILE
done

But I found I can iterate every element of second array in below way:

for EACH_FILE in ${FILE_LIST[*]}
do
    echo $EACH_FILE
done

In this question most answer explained how to use for loop in seconds way, but it didn't explain why my first way not working. Based on this answer's situation B, my first way should works fine, but it didn't. I am still pretty confuse why the second arraya can't iterate by the first way? Thankyou in advance!

fajin yu
  • 153
  • 1
  • 7
  • Because that's how array variables work in bash? – Shawn Aug 03 '21 at 03:43
  • Reading http://mywiki.wooledge.org/BashGuide/Arrays might be helpful, or the relevant parts of the official bash manual. – Shawn Aug 03 '21 at 03:44
  • Running your scripts through https://shellcheck.net is also a good way of finding problems (You have quite a few). – Shawn Aug 03 '21 at 03:50
  • @fajinyu : In your first case, `FILE_LIST` is not an array. In the second case, it is. – user1934428 Aug 03 '21 at 05:28
  • Thank you for your comment! I relized my problem, but I still wonder what `FILE_LIST` type is. A string? – fajin yu Aug 03 '21 at 05:49
  • 1
    use `typeset -p ` to see the contents of a variable; in your first case `typeset -p FILE_LIST` will show you a single string consisting of your filenames; in the 2nd case you'll see you've populated an array with the list of filenames – markp-fuso Aug 03 '21 at 13:54

1 Answers1

0

Small changes you need to take care of..

FILE_LIST+=(20191101.data.lz4
20191104.data.lz4
20191105.data.lz4
20191106.data.lz4
20191107.data.lz4
20191108.data.lz4
20191111.data.lz4
20191112.data.lz4
20191113.data.lz4
20191114.data.lz4
20191115.data.lz4
20191118.data.lz4
20191119.data.lz4)
for EACH_FILE in ${FILE_LIST[@]}
do
   echo $EACH_FILE
done

enter image description here

Jethan
  • 71
  • 5