So I have the following:

cat file | grep -E regex  

which gives a list of lines
Now I also have a for loop the produces a list of files
So it is like I have 2 arrays.
But how do I check in bash if both arrays have the same content? My bash version does not support associative arrays (4.2).
Should I find another way other than bash or is it doable with bash easily too?

I go over for i in foo/bar/* and record the paths so I essentially I have somewhere:

foo/bar/e etc  

So I essentially just want to re-run the for loop and check that I get exactly the same outcome.

  • 3
    Using grep or diffcould help. Add sample data to your post for more infos.
    – Michael D.
    Nov 29, 2018 at 12:15
  • 2
    filenames can span more than one line, unfortunately. Do you have any insight or control into what generates the contents of file? Or can you declare an assumption/restriction that your filenames will never have newlines in them?
    – Jeff Schaller
    Nov 29, 2018 at 13:39
  • @JeffSchaller: Yes no new lines in file names
    – Jim
    Nov 29, 2018 at 15:06
  • Some sample data / directory structure might help understand your request, as "a list of lines" does not necessarily equal "a list of files".
    – RudiC
    Nov 29, 2018 at 17:45
  • 1
    @JeffSchaller:I updated post
    – Jim
    Nov 29, 2018 at 18:22

1 Answer 1


Assuming your arrays are named "array1" and "array2", bash code to check for equality:

if [[ ${#array1[@]} -ne ${#array2[@]} ]]; then
    while IFS= read -r elem1 <&3; IFS= read -r elem2 <&4; do
        if [[ "$elem1" != "$elem2" ]]; then
    done 3< <(printf "%s\n" "${array1[@]}" | sort) \
         4< <(printf "%s\n" "${array2[@]}" | sort)
if $equal; then
    echo arrays have the same contents
    echo arrays have different contents

This will be (probably "much") slower than calling out to external tools.

diff <(grep -E regex file1) <(grep -E regex file2)
  • How do I initialize the arrays? Also the 2 < in the diff snippet are they right?
    – Jim
    Nov 29, 2018 at 15:58
  • Also what is 3 and 4?
    – Jim
    Nov 29, 2018 at 16:46
  • "3" and "4" are file descriptors: I want to be able to read from 2 different files in the same loop, so I red them from different file descriptors. Note how 3< after the loop corresponds with the <&3 in one of the read commands. Nov 30, 2018 at 0:17
  • The 2 < are correct: this bit 3< is the redirection and this bit <(...) is a process substitution Nov 30, 2018 at 0:18
  • I can't make that part work. I get an error as if diff us using the outputs of grep as files and says can't open them
    – Jim
    Nov 30, 2018 at 8:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .