Bash

傳遞 BASH 數組以區分文件內容

  • August 17, 2015

我有兩個bash數組,比如說:

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

我想用diff. 我怎樣才能傳遞數組,就好像它們是文件的內容一樣?

我嘗試了一些變化,但都失敗了:

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' )"

所需的輸出將是預期的diff -y,如果我將數組儲存到文件 a 和 b 中,我會得到:

diff a b
1        1
2        2
3      | A

(更少的空間可讀性)

出於速度原因,我想避免編寫中間文件,儘管我知道tmpfs偽文件是基於 RAM 的解決方法。

使用printf處理替換

diff -y  <(printf '%s\n' "${arr1[@]}")  <(printf '%s\n' "${arr2[@]}")
1                                                               1
2                                                               2
3                                                             | A

引用自:https://unix.stackexchange.com/questions/223666