Elarys
Elarys

Reputation: 669

zsh split directory into array

I'm trying to get an array containing the full current directory path in zsh. I'm currently using

local pwd="${PWD/#$HOME/~}"
pwd_list=(${(s:/:)pwd})

Which works except for one problem, it treats the starting / as a directory split too. I'd like my array to be like

instead of

I can see 2 ways of doing this but I'm unaware of how to do either in zsh. The first idea is to simple do a push and force a new element to the beginning (after the split).

The second, would be to alter the split to ignore the first / when parsing.

How can I resolve this to get an accurate directory path with minimal overhead into an array?

Upvotes: 1

Views: 2780

Answers (2)

Chris N
Chris N

Reputation: 949

I think you're thinking about it slightly wrong. If you split "/usr/lib/php" on "/", you should get four elements, the first of which is an empty string. If you join those array elements back together with "/", you get the original path. Trying to think of the first element of "/" means you're treating the splitting inconsistently, which will make everything else harder.

So the problem really is that you're only getting three elements instead of four: the empty first element is getting dropped. You can fix that by quoting, like this:

local pwd="${PWD/#$HOME/~}"
pwd_list=( "${(s:/:)pwd}" )

(The extra space next to the outer parentheses isn't necessary, but it makes it a little easier to read.) You can even combine that into one expression:

pwd_list=( "${(s:/:)${PWD/#$HOME/~}}" )

Upvotes: 2

Francisco
Francisco

Reputation: 4110

do you really need the first /? Assuming you're using a script to use the results of that, can't you just cd / to just start from there?

Anyways... is this what you want?

local pwd="${PWD/#$HOME/~}"
pwd_list=(${(s:/:)pwd})
pwd_list=('/' $pwd_list)

Upvotes: 4

Related Questions