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

Why do I get this output from my while read loop?

I wrote a script that used information from a CSV file to create a string from it. The script goes through each line, generates a string from it and appends it to the string of the previous line. So I end up with a long string that consists of information from all the lines. The result of the script should be to print only the final string.

My problem: As you can see in the output in the terminal, the script outputs every step (in this case 3) strings and not just the final one. Why is it like this?

This is my CSV:

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

42342;home;2020-01-12;2020-01-13
45235;work;2020-04-12;2020-04-13
68787;photo;2020-05-12;2020-05-13

This is my bash script:

getPhotosCommand(){
    com=""
    header="ID;DIR;START_DATE;END_DATE" 
    
    while read line; do
        IFS=';' read -r -a array <<< "$line"

        dir=${array[2]}
        start_date=${array[3]}
        end_date=${array[4]}

        newCom="cli-search -d $dir -s $start_date -e $end_date >> photos.txt && "
        com=$com$newCom
    
    echo "$com cli-search download -d $dir -p @photos.txt"

    done < $file_new_photos
}

Output in terminal:

cli-search -d home -s 2020-01-12 -e 2020-01-13 >> photos.txt && cli-search download -d home -p @photos.txt
cli-search -d home -s 2020-01-12 -e 2020-01-13 >> photos.txt && cli-search -d home -s 2020-04-12 -e 2020-04-13 >> photos.txt && cli-search download -d home -p @photos.txt
cli-search -d home -s 2020-01-12 -e 2020-01-13 >> photos.txt && cli-search -d home -s 2020-04-12 -e 2020-04-13 >> photos.txt && cli-search -d home -s 2020-05-12 -e 2020-05-13 >> photos.txt &&  cli-search download -d home -p @photos.txt

>Solution :

Each line is appending to the "$com" variable due to this line:

com=$com$newCom

and your echo statement looks like it should be outside of the loop, ie. after the done line.

If you would like just the last line, then move the echo statement.
If you would like 3 lines, change your echo statement to use $newCom instead of $com.

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