Totoc1001
Totoc1001

Reputation: 356

bash Reading array from file

I've already read a lot of questions concerning reading and writing in ARRAY in bash. I could not find the solution to my issue.

Actually, I've got a file that contains the path of a lot of files.

cat MyFile
> ~/toto/file1.txt
> ~/toto/file2.txt
> ~/toto/file3.txt
> ~/toto/file4.txt
> ~/toto/file5.txt

I fill an array ARRAY to contain this list:

readarray ARRAY < MyFile.txt

or

while IFS= read -r line
do 
   printf 'TOTO %s\n' "$line"
   ARRAY+=("${line}")
done <MyFile.txt

or

for line in $(cat ${MyFile.txt}) ; 
    do echo "==> $line"; 
    ARRAY+=($line) ; 
done

All those methods work well to fill the ARRAY,

echo "0: ${ARRAY[1]}"
echo "1: ${ARRAY[2]}"
> 0: ~/toto/file1.txt
> 1: ~/toto/file2.txt

This is awesome. but my problem is that if I try to diff the content of the file it does not work, it looks like the it does not expand the content of the file

diff ${ARRAY[1]} ${ARRAY[2]}
diff: ~/toto/file1.txt: No such file or directory
diff: ~/toto/file2.txt: No such file or directory

but when a print the content: echo diff ${ARRAY[1]} ${ARRAY[2]}

diff ~/toto/file1.txt ~/toto/file2.txt

and execute it I get the expected diff in the file diff ~/toto/file1.txt ~/toto/file2.txt

 3c3
 < Param = {'AAA', 'BBB'}
 ---
 > Param = {'AAA', 'CCC'}

whereas if I fill ARRAY manually this way:

ARRAY=(~/toto/file1.txt ~/toto/file2.txt)

diff works well.

Does anyone have an idea? Thanks a lot Regards, Thomas

Upvotes: 0

Views: 96

Answers (1)

Nic3500
Nic3500

Reputation: 8601

Tilde expansion does not happen when you use variable substitution from ${ARRAY[index]}.

Put the full path to the files in MyFile.txt and run your code again.

Upvotes: 1

Related Questions