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

时间:2018-11-09 09:55:20

标签: shell environment-variables path-variables

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

我最近编写了一个破折号/ bash函数来执行此操作,所以我想与他人共享它,因为显然其他地方都没有解决此问题。

1 个答案:

答案 0 :(得分:0)

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所做的所有shell扩展,也不知道如何重新创建它们。将来我可能会对此提供支持。