Md. Abid Hasan Md. Abid Hasan - 4 months ago 16
Bash Question

Reading files in nested loop in bash shell

I have a set of files.

file1, file2, file3

I need to read them pairwise in bash script using nested for loop.

file1, file2
file1, file3
file2, file3

How can I do that?


To go through all combinations of two files in the directory:

for i in "${!flist[@]}"
   for file2 in "${flist[@]:i+1}"
      echo "Files: $file1 $file2"

flist=(*) creates an array containing the names of all the files in the current directory.

for i in "${!flist[@]}"; do starts a loop over the indices of the array flist.

file1="${flist[i]}" assigns the name of the i-th file in flast to the variable file1.

for file2 in "${flist[@]:i+1}"; do starts a loop over all the file names in flist starting the i+1-th file.


Consider a directory with three files:

$ ls
file1  file2  file3

Now, let's run our command:

$ flist=(*); for i in "${!flist[@]}"; do file1="${flist[i]}"; for file2 in "${flist[@]:i+1}"; do echo "Files: $file1 $file2"; done; done
Files: file1 file2
Files: file1 file3
Files: file2 file3