Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bash echoes all itterations from for-loop into first value. Then continues normally

This is my first time posting anything here, so if I forget something or you need more info to answer my question, please let me know.

So I am trying to make a small bash script, that echoes all files in a folder into an array using a for-loop.

The snippet looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

romList=(*)

for line in *
do
    romList+="($(echo "$line\n"))"
done

Then when I try to echo out each value with this code:

for entry in "${romList[@]}"
do
    echo $entry
done

I get a result that looks like this:

$ file1 file2 file3
file2
file3

So for the first iteration it puts all of the files found into the first value and then continues as expected for the subsequent iterations.

For context I am trying to cleanup my roms folders, by removing language descriptions in the individual filenames. So my plan was to echo the filename into an array as a string, check up against an array of patterns and then remove that pattern from the string, so I can use it as a new filename.

That also means that the filenames have spaces and parenthesis in them, but I don’t understand if that should affect only the first iteration.

If you have another (read better) solution for achieving that, also please let me know.

>Solution :

To add a new element to an array, you need to parenthesise the right hand side.

romList+=("($(echo "$line\n"))")

Without it, it’s interpreted as string concatenation and it operates on the first element of the array.

But if there’s a file foo.txt, it already gets into the array in the first assignment (romList=(*)), why do you need (foo.txt\n) in the array, as well?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading