【问题标题】:How to add a dir to zsh PATH如何将目录添加到 zsh PATH
【发布时间】:2020-01-21 02:45:31
【问题描述】:

我是第一次尝试 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 不分割空白。那么,有没有办法实现我的目标?

【问题讨论】:

    标签: zsh


    【解决方案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
    }
    

    【讨论】:

      【解决方案2】:

      如果你需要在 zsh 中分割空间,你必须明确地说出来。例如,如果

      x="ab   cd"
      

      那么$x作为单个参数传递,但${(z)x}作为两个参数传递,abcd

      【讨论】:

        猜你喜欢
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 2014-09-15
        • 2011-08-07
        相关资源
        最近更新 更多