0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think how Cyrus' solution can work, because I don't think the ~ in variables will get expanded.
Actually it works, if you do not put the " around the ${ARRAY[INDEX]} variable subsititution. So diff <(cat ${ARRAY[0]}) <(cat ${ARRAY[1]}). That is because readarray does not remove the \n characters at the end of each line.
No, ~ is not expanded, and I think your reasoning about \n is false too ;-)
Well try it, I am not reasoning, I experiment and deduce. with the ", I clearly see the \n character. Without it, there are no \n. Or propose a more general solution. GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
The flaw in the reasoning is that \n being there will not cause tilde expansion. So Cyrus' solution cannot work, as long as ~ is in a variable. I would drop your sentence about Cyrus' solution. The rest of the answer (the first sentence and the last sentence) is good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.