1

Let's say I have string x:

/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy) file

I'd like to get array, where each file will be listed. My current code looks like this:

readarray -t y <<<"$x"

It works quite well, unless it gets to file name containing space, like (copy) file. Readarray splits that too and what I get in return is array y looking like this:

/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy)
file

How to prevent file name splitting?

7

Just to close this question and as advised in comments the reason that your array looks "splitted" is because of the way you print your array and not because your array is splitted by readarray. When you are in doubt for what really your array contains, i would suggest to use either declare -p (-p for print) or printf using double quotes.

Actually you should always double quote your variables no matter if you print them or you just use them in your scripts.

See these tests:

$ a="/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy) file"

$ echo "$a"
/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy) file

$ echo $a
/media/root/persistence/file /media/root/persistence/anotherfile /media/root/persistence/(copy) file

$ readarray -t y <<<"$a"
$ declare -p y
declare -a y=([0]="/media/root/persistence/file" [1]="/media/root/persistence/anotherfile" [2]="/media/root/persistence/(copy) file")

$ printf '%s\n' ${y[@]}
/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy)
file

$ printf '%s\n' "${y[@]}"
/media/root/persistence/file
/media/root/persistence/anotherfile
/media/root/persistence/(copy) file

As mentioned by don_crissti, you got this behavior because you did not double quote your variable.

To emphasize a bit on the importance of always quoting your variables, see this additional test:

$ b=" "

$ [ $b = " " ] && echo "ok" || echo "not ok"
bash: [: =: unary operator expected
not ok

$ [ "$b" = " " ] && echo "ok" || echo "not ok"
ok
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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