Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have two bash arrays, say:

arr1=( 1 2 3 )
arr2=( 1 2 A )

and I want to compare them using diff. How could I pass the arrays as if they were the contents of a file?

I tried a few variations, but all failed:

diff -y <$( echo ${arr1[@]} | tr ' ' '\n' ) <$( echo ${arr2[@]} | tr ' ' '\n' )
diff -y <${arr1[@]} <${arr2[@]}
diff -y $(<${arr2[@]}) $(<${arr1[@]})
diff -y  <<<"$( echo ${arr1[@]} | tr ' ' '\n' )" \
         <<<"$( echo ${arr2[@]} | tr ' ' '\n' )"

Desired output would be the expected from diff -y, which I get if I store the arrays into files a and b:

diff a b
 1        1
 2        2
 3      | A

(less spaces for readability)

I would like to avoid writing intermediate files for speed reasons, although I am aware of tmpfs pseudo files as RAM-based workaround.

share|improve this question
    
<<< is implemented by writing a file in /tmp, and redirecting input from that, unfortunately. One of the inputs could be a pipe, though. – Peter Cordes Aug 17 '15 at 13:52
up vote 9 down vote accepted

Using printf and process substitution

diff -y  <(printf '%s\n' "${arr1[@]}")  <(printf '%s\n' "${arr2[@]}")
1                                                               1
2                                                               2
3                                                             | A
share|improve this answer
    
I see <( ) is the trick, that way also my <( echo ${arr1[@]} | tr ' ' '\n' ) works. I'll keep the "process substitution" keyword in mind. – Fiximan Aug 17 '15 at 11:57
3  
@Fiximan, your tr pipeline will break for any array element containing spaces. printf is the idiomatic way to print an array one element per line. – glenn jackman Aug 17 '15 at 12:44
    
I agree printf is saver if formulating it more general, although I will not have elements with spaces. Also every pipe avoided should be faster, so that also speaks for printf .... However, my main concern was getting the <( ) solution. – Fiximan Aug 17 '15 at 12:46
4  
"I will not have elements with spaces." <- Famous last words! – bishop Aug 17 '15 at 14:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.