0

I want to save all filename in ~/mount that is a csv file. Below is my code

 #!/bin/bash


IFS=$'\n' ARR=`find ~/mount -name '*.csv'`;
for VALUE in "${ARR[@]}";
do
    echo "<----$VALUE---->";
done

This should print out

<----foo.csv---->
<----bar.csv---->

but instead, it prints out

<----foo.csv
bar.csv---->

How can I fix this? or is there another way? Thank you.

chi.ho
  • 11
  • 1
  • 1
    Does this answer your question? [How to loop through file names returned by find?](https://stackoverflow.com/questions/9612090/how-to-loop-through-file-names-returned-by-find) – Julien Sorin Sep 09 '21 at 07:48
  • @JulienSorin This is what I was looking for. Thanks – chi.ho Sep 09 '21 at 07:51
  • @chi.ho : You need to define an array. Your variable `ARR` is a scalar, but in the `for` statement, you use it as if it were an array. – user1934428 Sep 09 '21 at 08:00

1 Answers1

1

Arrays are defined by using

name=( .... )

Hence, you could define

ARR=( $(find .... ) )

Perhaps a better alternative would be to not use find at all:

shopt -s globstar # to enable **
ARR=( ~/mount/**/*.csv )
shopt -u globstar 

This would even catch the border case, that you have filenames with embedded newline characters.

user1934428
  • 19,864
  • 7
  • 42
  • 87
  • 1
    Did you mean `extglob` or `globstar`? Also, what if the user already has `shopt -s globstar` in their bashrc? You wouldn't want to undo it. – k314159 Sep 09 '21 at 08:13
  • 1
    Ah, you are right - from the man page, I see that it is globstar. I didn't notice, because my bash (version 4.4.12(3)) strangely expands `**` in this way, even if extglob and globstar are off; don't know why. The `.bashrc` should not matter, because the code seems to be used in a script, and .bashrc is only relevant in interactive shells. Furthermore, if the use indeed has set this switch before, he likely knows enough on that subject that he doesn't need any handholding for restoring the original value. – user1934428 Sep 09 '21 at 08:20