zshzsh-zle

Insert item into zsh array


Let's say I have an array defined as such:

  typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(
    os_icon
    dir
    vcs
    newline
    prompt_char
  )

Now I want to insert an item my_item into the array after vcs. I don't know what index vcs is at, all I know is that I want to insert it right after vcs

I tried

POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS:s/vcs/vcs my_item})

But for some reason that does not work. The followed does work for substitution:

POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS:s/vcs/my_item})

But of course will remove vcs.... I'm obviously not getting the space correct, but can't seem to get it right.


Solution

  • If you knew the index, you could simply assign an array slice to the index of vcs:

    POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[2]=(vcs my_item)
    

    As you don't know the index, but are sure the element can only exist once, just assign to the first matching index:

    POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[(i)vcs]}]=(vcs my_item)
    

    Transcript of a shell session to try this out:

     /tmp                                                                                                                                                 [9:10]
     ❯ typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(
        os_icon
        dir
        vcs
        newline
        prompt_char
      )
    
    
     /tmp                                                                                                                                                 [9:10]
     ❯ echo ${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[3]}
    vcs
    
     /tmp                                                                                                                                                 [9:10]
     ❯ echo ${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[4]}
    newline
    
     /tmp                                                                                                                                                 [9:10]
     ❯ POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[(i)vcs]}]=(vcs my_item)
    
     /tmp                                                                                                                                                 [9:10]
     ❯ echo ${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[3]}
    vcs
    
     /tmp                                                                                                                                                 [9:10]
     ❯ echo ${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[4]}
    my_item
    
     /tmp                                                                                                                                                 [9:10]
     ❯ echo ${POWERLEVEL9K_LEFT_PROMPT_ELEMENTS[5]}
    newline
    ``