Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZSH - How can I join an array using the colon ":" character/escape colon character?

Tags:

zsh

I don't know how to escape colons when using the zsh j:string: array expansion sequence.

In my ~/.zshrc I find it pleasing to build up my PATH as an array.

path_array=(
  /sbin
  /usr/sbin
  $HOME/brew/bin
  /bin
  /usr/bin
  /usr/local/bin
  /opt/X11/bin
)

#https://unix.stackexchange.com/questions/23208/building-paths-robustly/23241#23241
#export PATH=${(j:::)path_array}

There are plenty of examples of how to join an array on other characters but unfortunately I can't see how to escape the character : so I can use it in this sequence.

The result is : zsh: error in flags

Using another character | it works fine

echo ${(j:|:)path_array}

/sbin|/usr/sbin|/Users/mf/brew/bin|/bin|/usr/bin|/usr/local/bin|/opt/X11/bin
like image 485
merge failure Avatar asked Dec 09 '25 12:12

merge failure


1 Answers

Re zsh: error in flags: This one is easy. You can use any other delimiter in your parameter expansion flags:

$ arr=(/usr/local/bin /usr/bin /usr/sbin /bin)
$ print -R ${(j|:|)arr}
/usr/local/bin:/usr/bin:/usr/sbin:/bin

Your bigger problem is you shouldn't need to do this in the first place. Zsh specifically has a lowercase path variable which is the array counterpart of the scalar PATH. Setting one automatically updates the other. See http://zsh.sourceforge.net/Doc/Release/Parameters.html#index-path. (Similarly there are cdpath, fpath, mailpath, manpath, etc.) Here's an example:

$ path=(/usr/bin /bin)
$ print -R $PATH
/usr/bin:/bin
$ path=(/usr/local/bin /usr/bin /usr/sbin /bin)
$ print -R $PATH
/usr/local/bin:/usr/bin:/usr/sbin:/bin
$ PATH=/usr/bin:/bin
$ print -R $path
/usr/bin /bin

You get the idea.

As an aside, I also recommend

typeset -gU path

to remove duplicates, because it's not uncommon to insert duplicate entries into path (when you insert paths the right way: prepend to the existing array).

like image 68
4ae1e1 Avatar answered Dec 13 '25 12:12

4ae1e1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!