kkd92 kkd92 - 4 months ago 8
Bash Question

Bash Loop Help (want to echo aa, bb, cc)

Loop logic always confuses me, this is probably a simple solution. My current loop:

for i in a b; do for j in a b; do echo $i$j; done; done


This loop prints the following output:

aa
ab
ba
bb


I would like for it to only print:

aa
bb


I just want it to match up the first two letters, then the second two letters and so on. Eventually I want to expand this over files in two different directories. So I want to print the first file name in dir1, then the first in dir2. Then the 2nd in dir1 and the 2nd in dir2. Just trying to simplify that and understand the logic first.

Answer

I would suggest using arrays to solve your problem:

dir1_files=( dir1/* )
dir2_files=( dir2/* )

for (( i = 0; i < ${#dir1_files[@]}; ++i )); do
    echo "${dir1_files[i]} ${dir2_files[i]}" 
done

This assumes that the number of files in each directory is the same.