Search code examples
zsh

How to add a dir to zsh PATH


I am a bash user trying zsh for the first time. In bash, I have functions to manipulate paths such as appending a directory to the path only if

  1. that directory exists, and
  2. if that directory is not currently in the path.

For bash, I have something like:

# =============================================================================
# Returns true (0) if element is in the list, false (1) if not
# $1 = list, $2 = element
# =============================================================================
function lcontains() {
    found=1  # 1=not found, 0=found
    local IFS=:
    for e in $1
    do
        if [[ $2 == $e ]]
        then
            found=0
            break
        fi
    done

    return $found
}

# =============================================================================
# Appends into a list an element
# $1 = list, $2 = element
# =============================================================================
function lappend() {
    if [[ -d $2 ]] && ! lcontains "$1" "$2"
    then
        echo $1:$2
    else
        echo $1
    fi
}

# Usage:
export PATH=$(lappend $PATH ~/bin)

# Add the same path again, and result in no duplication
export PATH=$(lappend $PATH ~/bin) 

The trouble is, in zsh, the lcontains function does not work because zsh does not split white space by default. So, is there a way to accomplish my objective?


Solution

  • General solution: split with IFS.

    function lcontains() {
      local IFS=':'
      local found=1  # 1=not found, 0=found
      local e
      for e in $(echo "$1")
      do
        if [[ $2 == $e ]]
        then
          found=0
          break
        fi
      done
    
      return $found
    }
    

    ZSH only solution: split by Parameter Expansion Flag s

    function lcontains() {
      local found=1  # 1=not found, 0=found
      local e
      for e in "${(@s#:#)1}"
      do
        if [[ $2 == $e ]]
        then
          found=0
          break
        fi
      done
    
      return $found
    }