如何将目录添加到zsh PATH

时间:2019-09-20 04:04:52

标签: zsh

我是第一次尝试zsh的bash用户。在bash中,我具有操作路径的功能,例如仅在以下情况下才将目录追加到路径中:

  1. 该目录存在,并且
  2. 该目录当前不在路径中。

对于bash,我有类似的东西:

# =============================================================================
# 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) 

问题是,在zsh中,lcontains函数不起作用,因为zsh默认情况下不会拆分空格。那么,有没有办法实现我的目标?

2 个答案:

答案 0 :(得分:1)

一般解决方案:用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解决方案:除以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
}

答案 1 :(得分:0)

如果需要在zsh中拆分空间,则必须明确地说出这一点。例如,如果

x="ab   cd"

然后$x作为单个参数传递,但是${(z)x}作为两个参数abcd传递。