Copy variable to array

Johnny Rosenberg gurus.knugum at gmail.com
Sun Jun 1 16:57:29 UTC 2014


2014-06-01 18:46 GMT+02:00 Johnny Rosenberg <gurus.knugum at gmail.com>:

> I have a variable that contains a path. Now I want to copy every single
> directory to an array like this:
> x=./abc/def/ghi/jkl/mno
> # Do something here to copy x to the array y…
> echo ${y[3]} # Should print ”def”.
>
> Here's the result of my best (?) try:
> $ x="./abc/def/ghi/jkl/mno"; IFS='/'; y=$x; echo ${y[0]}; echo ${#y[@]};
> IFS=$'\n'
> . abc def ghi jkl mno
> 1
> $
>
> Here's what I hoped would happen:
> $ x="./abc/def/ghi/jkl/mno"; IFS='/'; y=$x; echo ${y[0]}; echo ${#y[@]};
> IFS=$'\n'
> .
> 6
> $
>
> What am I doing wrong? It seems to work if I read the path from a file
> with ”read -r -a”, why not from a variable?
>
>
> Johnny Rosenberg
>

After some further ”googling” I finally found the answer:
$ x="./abc/def/ghi/jkl/mno"; IFS='/'; y=(${x}); echo ${y[0]}; echo
${#y[@]}; IFS=$'\n'
.
6
$

Seems like there is a special array syntax, using those parentheses –
”y=(${x})”.
If anyone have anything else to say in this matter, please do. I want to
learn.


Johnny Rosenberg
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/ubuntu-users/attachments/20140601/989122f1/attachment.html>


More information about the ubuntu-users mailing list