Hai Vu
Hai Vu

Reputation: 40773

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?

Upvotes: 0

Views: 198

Answers (2)

Simba
Simba

Reputation: 27758

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
}

Upvotes: 1

user1934428
user1934428

Reputation: 22366

If you need splitting on space in zsh, you have to say this explicitly. For example, if

x="ab   cd"

then $x is passed as single parameter, but ${(z)x} is passed as two parmeters, ab and cd.

Upvotes: 0

Related Questions