kkd92 kkd92 - 1 year ago 51
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:


I would like for it to only print:


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 Source

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]}" 

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download