Shell 从`$PATH`环境变量中删除不存在的目录

Shell 从`$PATH`环境变量中删除不存在的目录,shell,environment-variables,path-variables,Shell,Environment Variables,Path Variables,从PATH环境变量中删除不存在的目录,这是一种管理路径的好方法。添加所有可能存在的位置,然后删除所有不存在的位置。这比添加时检查目录的存在要枯燥得多 我最近编写了一个dash/bash函数来实现这一点,所以我想与大家分享一下,因为显然这在其他任何地方都没有解决过。path\u checkdir 此代码与破折号兼容 path_checkdir() { keep_="=" remove_="_" help=' Usage: path_checkdir [-v] [-K =

PATH
环境变量中删除不存在的目录,这是一种管理路径的好方法。添加所有可能存在的位置,然后删除所有不存在的位置。这比添加时检查目录的存在要枯燥得多

我最近编写了一个dash/bash函数来实现这一点,所以我想与大家分享一下,因为显然这在其他任何地方都没有解决过。

path\u 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
的某些路径包含
~
,它们将无法正确解释,并将被删除。我不知道所有的shell扩展对
$PATH
都做了什么,也不知道如何重新创建它们。我可能会在将来为它添加支持