shopt -s nullglob
dir1names=( Dir1/* )
dir2names=( Dir2/* )
while [ "${#dir1names[@]}" -gt 0 ] &&
[ "${#dir2names[@]}" -gt 0 ]
do
printf '%s\n' "${dir1names[0]##*/}"
printf '%s\n' "${dir2names[0]##*/}"
dir1names=( "${dir1names[@]:1}" )
dir2names=( "${dir2names[@]:1}" )
done
This uses bash
to get all the pathnames from each directory into two arrays. It then prints the filename portion of these pathnames (like ls
would do), alternating between the arrays, and deletes the printed entires from the arrays. It stops when one of the arrays is completely empty.
The nullglob
shell option makes non-matched globbing patterns expand to nothing rather than remain unexpanded.
Testing:
$ tree
.
|-- Dir1
| |-- file-1
| |-- file-2
| |-- file-3
| `-- file-4
|-- Dir2
| |-- otherfile-1
| |-- otherfile-2
| |-- otherfile-3
| |-- otherfile-4
| |-- otherfile-5
| `-- otherfile-6
`-- script.sh
2 directories, 11 files
$ bash script.sh
file-1
otherfile-1
file-2
otherfile-2
file-3
otherfile-3
file-4
otherfile-4
If this is actually about pairing up files according to their names, so that a file in one directory are paired with the corresponding file in another (as is sometimes done in e.g. bioinformatics applications, it seems), then you are better off just iterating over one of the sets and then constructing the name of the corresponding files from the other set.
Assuming the files are called something_R1_more
and something_R2_more
where something
and more
is identifying a particular R1
-R2
pair of files.
for r1 in dir1/*_R1_*; do
r2=${r1##*/} # dir1/something_R1_more --> something_R1_more
r2=dir2/${r2/_R1_/_R2_} # something_R1_more --> dir2/something_R2_more
if [ ! -f "$r2" ]; then
printf '%s not found\n' "$r2" >&2
exit 1
fi
# process "$r1" and "$r2" here
done