【问题标题】:Remove non-existing directories from `$PATH` environment variable从 `$PATH` 环境变量中删除不存在的目录
【发布时间】:2019-04-12 21:21:45
【问题描述】:

PATH 环境变量中删除不存在的目录,这是管理 PATH 的一种巧妙方法。您添加所有可能存在的位置,然后删除所有不存在的位置。这比在添加时检查目录是否存在要简单得多。

我最近编写了一个 dash/bash 函数来执行此操作,所以我想我会分享它,因为显然这在其他任何地方都没有得到解决。

【问题讨论】:

    标签: shell environment-variables path-variables


    【解决方案1】:

    path_checkdir

    此代码与破折号兼容。

    path_checkdir() {
    
        keep_="="
        remove_="_"
    
        help='
    Usage: path_checkdir [-v] [-K =] [-R _] [-i $'\n']
    
        -i ignore_this_path
    Accept the specified path without checking the existence of the directory.
    /!\ Beware, specifying it more than once will overwrite the preceding value.
    I use it to keep single newlines in my $PATH.
    
        -v
    Tell which directories are kept and which are removed.
    
        -K marker_keep_path
        -R marker_remove_path
    Replace the default values (= for -K and _ for -R) used by -v to tell what is
    kept and what is removed.
    '
    
        while [ $# -gt 0 ]
        do
            case "$1" in
            "-v") verbose=t;;
            "-i") shift; ignore="i$1";;
            "-K") shift; keep_="$1";;
            "-R") shift; remove_="$1";;
            "-h"|"--help") echo "$help"
            esac
            shift
        done
    
        # /!\ IFS characters are stripped when using `read`
        local oIFS="$IFS"
        IFS=''
        # /!\ Beware pipes. They imply subshells
        # The usuall alternative is to use process substitution, but it
        # won't work with dash, so I used file descriptor redirections
        # instead.
        {
        PATH="$(echo "$PATH" | {
        P=""
        while read -rd: dir
        do
            if [ "i$dir" = "$ignore" ] || [ -d "$dir" ]
            then
                # If -v is provided, be verbose about what is kept (=) and
                # what is removed (_).
                if [ $verbose ]
                then echo "$keep_$dir" >&3
                fi
                P="$P:$dir"
            else
                if [ $verbose ]
                then echo "$remove_$dir" >&3
                fi
            fi
        done
        echo "${P:1}"; })"
        } 3>&1
        IFS="$IFS"
    }
    

    现在,还有很多需要改进的地方。它只接受一个路径异常,而接受任何数字并且可能也支持通配符模式会很棒。更重要的是,如果$PATH 的某些路径包含~,它们将不会被正确解释并被删除。我不确定对$PATH 所做的所有外壳扩展是什么,也不知道如何重新创建它们。将来我可能会添加对此的支持。

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2011-03-05
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多