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 are loop generated Bash array values concatonated together?

Im writing a short script to automate output filenames. The testing folder has the following files:

  • test_file_1.fa
  • test_file_2.fa
  • test_file_3.fa

So far, I have the following:

#!/bin/bash

filenames=$(ls *.fa*)
output_filenames=$()
output_suffix=".output.faa"

for name in $filenames
do
        output_filenames+=$name$output_suffix
done

for name in $output_filenames
do 
        echo $name
done

The output for this is:

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

test_file_1.fa.output.faatest_file_2.fa.output.faatest_file_3.fa.output.faa

Why does this loop ‘stick’ all of the filenames together as one array variable?

>Solution :

shell arrays require particular syntax.

output_filenames=()            # not $()
output_suffix=".output.faa"

for name in *.fa*              # don't parse `ls`
do
        output_filenames+=("$name$output_suffix")   # parentheses required
done

for name in "${output_filenames[@]}"    # braces and index and quotes required
do 
        echo "$name"
done

https://tldp.org/LDP/abs/html/arrays.html has more examples of using arrays.

"Don’t parse ls" => https://mywiki.wooledge.org/ParsingLs

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