How do I manipulate $PATH elements in shell scripts?

前端 未结 12 1080
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:03

Is there a idiomatic way of removing elements from PATH-like shell variables?

That is I want to take

PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:         


        
12条回答
  •  自闭症患者
    2020-11-28 04:36

    • Order of PATH is not distrubed
    • Handles corner cases like empty path, space in path gracefully
    • Partial match of dir does not give false positives
    • Treats path at head and tail of PATH in proper ways. No : garbage and such.

    Say you have /foo:/some/path:/some/path/dir1:/some/path/dir2:/bar and you want to replace /some/path Then it correctly replaces "/some/path" but leaves "/some/path/dir1" or "/some/path/dir2", as what you would expect.

    function __path_add(){  
        if [ -d "$1" ] ; then  
            local D=":${PATH}:";   
            [ "${D/:$1:/:}" == "$D" ] && PATH="$PATH:$1";  
            PATH="${PATH/#:/}";  
            export PATH="${PATH/%:/}";  
        fi  
    }
    function __path_remove(){  
        local D=":${PATH}:";  
        [ "${D/:$1:/:}" != "$D" ] && PATH="${D/:$1:/:}";  
        PATH="${PATH/#:/}";  
        export PATH="${PATH/%:/}";  
    }  
    # Just for the shake of completeness
    function __path_replace(){  
        if [ -d "$2" ] ; then  
            local D=":${PATH}:";   
            if [ "${D/:$1:/:}" != "$D" ] ; then
                PATH="${D/:$1:/:$2:}";  
                PATH="${PATH/#:/}";  
                export PATH="${PATH/%:/}";  
            fi
        fi  
    }  
    

    Related post What is the most elegant way to remove a path from the $PATH variable in Bash?

提交回复
热议问题