Programming

$ PATH 변수에서 중복 경로 제거

procodes 2020. 7. 11. 11:53
반응형

$ PATH 변수에서 중복 경로 제거


$ PATH 변수에 동일한 경로를 6 번 정의했습니다.

작동하는지 확인하기 위해 로그 아웃하지 않았습니다.

중복을 어떻게 제거 할 수 있습니까?

$ PATH 변수는 다음과 같습니다.

echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/flacs/Programmes/USFOS/bin:/home/flacs/Programmes/USFOS/bin:/home/flacs/Programmes/USFOS/bin:/home/flacs/Programmes/USFOS/bin:/home/flacs/Programmes/USFOS/bin:/home/flacs/Programmes/USFOS/bin

어떻게 재설정합니까?

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

당신은 단지 실행 :

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

그것은 현재 세션에 대한 것입니다. 영구적으로 변경하려면 시스템과 사용자의 요구에 맞는 것을 .bashrc, bash.bashrc, / etc / profile에 영구적으로 추가하십시오.


당신이 배쉬를 사용하는 경우, 당신은 또한의 당신이 디렉토리를 제거 할 말을하자, 경우 다음 작업을 수행 할 수 있습니다 /home/wrong/dir/귀하의에서 PATH변수 :

PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`

Linux : $ PATH 변수에서 중복 경로 제거

Linux From Scratch는 / etc / profile 에이 기능있습니다.

# Functions to help us manage paths.  Second argument is the name of the
# path variable to be modified (default: PATH)
pathremove () {
        local IFS=':'
        local NEWPATH
        local DIR
        local PATHVARIABLE=${2:-PATH}
        for DIR in ${!PATHVARIABLE} ; do
                if [ "$DIR" != "$1" ] ; then
                  NEWPATH=${NEWPATH:+$NEWPATH:}$DIR
                fi
        done
        export $PATHVARIABLE="$NEWPATH"
}

경로에 추가하기 위해 다음 기능과 함께 사용되므로 중복하지 마십시오.

pathprepend () {
        pathremove $1 $2
        local PATHVARIABLE=${2:-PATH}
        export $PATHVARIABLE="$1${!PATHVARIABLE:+:${!PATHVARIABLE}}"
}

pathappend () {
        pathremove $1 $2
        local PATHVARIABLE=${2:-PATH}
        export $PATHVARIABLE="${!PATHVARIABLE:+${!PATHVARIABLE}:}$1"
}

간단한 사용법은 pathremove디렉토리 경로를 제거하는 것입니다. 그러나 정확히 일치해야합니다.

$ pathremove /home/username/anaconda3/bin

그러면 해당 디렉토리의 각 인스턴스가 경로에서 제거됩니다.

경로에 디렉토리를 원하지만 중복성이없는 경우 다른 기능 중 하나를 사용할 수 있습니다 (예 : 특정 경우).

$ pathprepend /usr/local/sbin
$ pathappend /usr/local/bin
$ pathappend /usr/sbin
$ pathappend /usr/bin
$ pathappend /sbin
$ pathappend /bin
$ pathappend /usr/games

그러나 가독성이 문제가되지 않는 한이 시점에서 다음을 수행하는 것이 좋습니다.

$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

위의 내용은 사람에게 알려진 모든 껍질에서 작동합니까?

나는에 일에 위의 가정 것이다 sh, dash그리고 bash적어도. 나는 그것이 작동하지 않습니다 배울 놀랄 것 csh, fish', orksh`을. Windows 명령 셸 또는 Powershell에서 작동하는지 의심합니다.

Python을 사용하는 경우 다음과 같은 종류의 명령은 직접 요청 된 작업을 수행해야합니다 (즉, 중복 경로 제거).

$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')
print(':'.join(sorted(set(path), key=path.index)))
" )

A one-liner (to sidestep multiline issues):

$ PATH=$( python -c "import os; path = os.environ['PATH'].split(':'); print(':'.join(sorted(set(path), key=path.index)))" )

The above removes later redundant paths. To remove earlier redundant paths, use a reversed list's index and reverse it again:

$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')[::-1]
print(':'.join(sorted(set(path), key=path.index, reverse=True)))
" )

Here is a one line code that cleans up the PATH

  • It does not disturb the order of the PATH, just removes duplicates
  • Treats : and empth PATH gracefully
  • No special characters used, so does not require escape
  • Uses /bin/awk so it works even when PATH is broken

    export PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";}
    {sub(sprintf("%c$",10),"");if(A[$0]){}else{A[$0]=1;
    printf(((NR==1)?"":":")$0)}}')";
    

In bash you simply can ${var/find/replace}

PATH=${PATH/%:\/home\/wrong\/dir\//}

Or in this case (as the replace bit is empty) just:

PATH=${PATH%:\/home\/wrong\/dir\/}

I came here first but went else ware as I thought there would be a parameter expansion to do this. Easier than sed!.

How to replace placeholder character or word in variable with value from another variable in Bash?


If you just want to remove any duplicate paths, I use this script I wrote a while back since I was having trouble with multiple perl5/bin paths:

#!/bin/bash
#
# path-cleanup
#
# This must be run as "source path-cleanup" or ". path-cleanup"
# so the current shell gets the changes.

pathlist=`echo $PATH | sed 's/:/\n/g' | uniq`

# echo "Starting PATH: $PATH"
# echo "pathlist: $pathlist"
unset PATH
# echo "After unset, PATH: $PATH"
for dir in $pathlist
do
    if test -d $dir ; then
        if test -z $PATH; then
            PATH=$dir
        else
            PATH=$PATH:$dir
        fi
    fi
done
export PATH
# echo "After loop, PATH: $PATH"

And I put it in my ~/.profile at the end. Since I use BASH almost exclusively, I haven't tried it in other shells.


Assuming your shell is Bash, you can set the path with

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

but like Levon said in another answer, as soon as you terminate the shell the changes will be gone. You probably want to set up your PATH in ~/.bash_profile or ~/.bashrc.


For an easy copy-paste template I use this Perl snippet:

PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`

This way you don't need to escape the slashes for the substitute operator.


  1. Just echo $PATH
  2. copy details into a text editor
  3. remove unwanted entries
  4. PATH= # pass new list of entries

There are no standard tools to "edit" the value of $PATH (i.e. "add folder only when it doesn't already exists" or "remove this folder").

To check what the path would be when you login next time, use telnet localhost (or telnet 127.0.0.1). It will then ask for your username and password.

This gives you a new login shell (i.e. a completely new one that doesn't inherit anything from the current environment).

You can check the value of the $PATH there and edit your rc files until it is correct. This is also useful to see whether you could login again at all after making a change to an important file.


How did you add these duplicate paths to your PATH variable? You must have edited one of your . files. (.tcshrc, or .bashrc, etc depending on your particular system/shell). The way to fix it is to edit the file again and remove the duplicate paths.

If you didn't edit any files, and you you must have modified the PATH interactively. In that case the changes won't "stick", ie if you open another shell, or log out and log back in, the changes will be gone automatically.

Note that there are some system wide config files too, but it's unlikely you modified those, so most likely you'll be changing files in your personal home directory (if you want to make those changes permanent once you settle on a set of paths)

참고URL : https://stackoverflow.com/questions/11650840/remove-redundant-paths-from-path-variable

반응형