Home > Software design >  Why are loop generated Bash array values concatenated together?
Why are loop generated Bash array values concatenated together?

Time:12-14

I'm 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:

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?

CodePudding user response:

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

  • Related