ZSH issue with colorized prompt and double slash, i.e “//” appearing when I am into root

coloritermpathterminalzsh

I am faced to a problem of appearing slash / appearing double slash into PS1 when I am located on root / .

I explain more precisely, I have in .zshrc :

setopt PROMPT_SUBST
slash_color () { dirs | awk -F "/" ' {for (i=1; i<=NF; i++) {printf "\033[38;5;75m"$i"\033[38;5;206m" "/"}} '; }
PS1='%F{13}|%F{green}%n@%F{cyan}%m%F{13}|%f%T%F{13}|$(slash_color)%F{13}|%F{7} '

The goal was to colorize each slash of the current PATH.

This way, when I go to a deeper directory, I get :

prompt colorized with slash

But a problem remains when I do : $ cd /, I get the following result, i.e a double slash representing the current path and I don't know to handle this to have only a single path :

double slash issue

If someone could help me to get only one slash when I am located on root, i.e / ?

Best Answer

Change the for loop from

for (i=1; i<=NF; i++) \
 printf blue $i pink "/"; \
printf "\n"

to

for (i=1; i<NF; i++) \
 printf blue $i pink "/"; \
printf blue $NF pink; \
printf "\n"
  • notice the change in <=<
  • Take care of semi-colons.

or use some help from searching to get an if else condition for which the pseudocode (not correct bash syntax) is:

for all i<=NF:
 if (i<NF):
   printf blue $i pink "/" ;
 else:
   printf blue $i pink ;
printf "\n";