Linux 从 $PATH 变量中删除冗余路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11650840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove redundant paths from $PATH variable
提问by charles hendry
I have defined the same path in the $PATH variable 6 times.
我在 $PATH 变量中定义了 6 次相同的路径。
I wasn't logging out to check whether it worked.
我没有注销以检查它是否有效。
How can I remove the duplicates?
如何删除重复项?
The $PATH variable looks like this:
$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
How would I reset it to just
我如何将它重置为只是
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
采纳答案by hovanessyan
You just execute:
你只需执行:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
that would be for the current session, if you want to change permanently add it to any .bashrc, bash.bashrc, /etc/profile - whatever fits your system and user needs.
这将用于当前会话,如果您想永久更改将其添加到任何 .bashrc、bash.bashrc、/etc/profile - 任何适合您的系统和用户需求的文件。
Note: This is for Linux. We'll make this clear for new coders. (` , ') Don't try to SET = these.
注意:这是针对 Linux 的。我们将为新编码人员明确这一点。(` , ') 不要尝试 SET = 这些。
回答by Levon
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.
您是如何将这些重复路径添加到 PATH 变量中的?您必须编辑过其中一个.
文件。( .tcshrc
, 或.bashrc
等取决于您的特定系统/外壳)。修复它的方法是再次编辑文件并删除重复的路径。
If you didn'tedit 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.
如果您没有编辑任何文件,并且您必须以交互方式修改了 PATH。在这种情况下,更改不会“保持不变”,即如果您打开另一个 shell,或者注销并重新登录,更改将自动消失。
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)
请注意,还有一些系统范围的配置文件,但您不太可能修改它们,因此很可能您将更改个人主目录中的文件(如果您想在确定一组路径后使这些更改永久生效)
回答by Leo
Assuming your shell is Bash, you can set the path with
假设你的 shell 是 Bash,你可以设置路径
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
.
但是就像 Levon 在另一个答案中所说的那样,只要您终止 shell,更改就会消失。您可能想要设置您的PATH
in~/.bash_profile
或~/.bashrc
.
回答by Aaron Digulla
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").
没有标准工具可以“编辑” 的值$PATH
(即“仅当文件夹不存在时才添加文件夹”或“删除此文件夹”)。
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.
要检查下次登录时的路径,请使用telnet localhost
(或telnet 127.0.0.1
)。然后它会询问您的用户名和密码。
This gives you a new login shell (i.e. a completely new one that doesn't inherit anything from the current environment).
这为您提供了一个新的登录 shell(即一个全新的,不会从当前环境继承任何东西)。
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.
您可以检查$PATH
那里的值并编辑您的 rc 文件,直到它正确为止。这对于查看在更改重要文件后是否可以再次登录也很有用。
回答by GreenFox
Here is a one line code that cleans up the PATH
这是清理 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 brokenexport PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";} {sub(sprintf("%c$",10),"");if(A[
]){}else{A[export PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";} {sub(sprintf("%c$",10),"");if(A[
]){}else{A[PATH=`echo $PATH | sed -e 's/:\/home\/wrong\/dir\/$//'`
]=1; printf(((NR==1)?"":":")PATH=${PATH/%:\/home\/wrong\/dir\//}
)}}')";PATH=${PATH%:\/home\/wrong\/dir\/}
]=1; printf(((NR==1)?"":":")PATH=`echo $PATH | perl -pe s:/path/to/be/excluded::`
)}}')";# 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" != "" ] ; then NEWPATH=${NEWPATH:+$NEWPATH:}$DIR fi done export $PATHVARIABLE="$NEWPATH" }
- 它不会扰乱 PATH 的顺序,只是删除重复项
- Treats : 并优雅地清空 PATH
- 没有使用特殊字符,所以不需要转义
使用,
/bin/awk
因此即使 PATH 损坏也能正常工作pathprepend () { pathremove local PATHVARIABLE=${2:-PATH} export $PATHVARIABLE="${!PATHVARIABLE:+:${!PATHVARIABLE}}" } pathappend () { pathremove local PATHVARIABLE=${2:-PATH} export $PATHVARIABLE="${!PATHVARIABLE:+${!PATHVARIABLE}:}" }
回答by sufinawaz
If you're using Bash, you can also do the following if, let's say, you want to remove the directory /home/wrong/dir/
from your PATH
variable:
如果您使用 Bash,如果您想/home/wrong/dir/
从PATH
变量中删除目录,您还可以执行以下操作:
$ pathremove /home/username/anaconda3/bin
回答by sabgenton
In bash you simply can ${var/find/replace}
在 bash 中,您只需 ${var/find/replace}
$ pathprepend /usr/local/sbin
$ pathappend /usr/local/bin
$ pathappend /usr/sbin
$ pathappend /usr/bin
$ pathappend /sbin
$ pathappend /bin
$ pathappend /usr/games
Or in this case (as the replace bit is empty) just:
或者在这种情况下(因为替换位为空)只是:
$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
I came here first but went else ware as I thought there would be a parameter expansionto do this. Easier than sed!.
我首先来到这里,但因为我认为会有一个参数扩展来做到这一点,所以去了其他地方。比 sed 更容易!
How to replace placeholder character or word in variable with value from another variable in Bash?
回答by Alexander Shcheblikin
For an easy copy-paste template I use this Perl snippet:
对于一个简单的复制粘贴模板,我使用这个 Perl 片段:
$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')
print(':'.join(sorted(set(path), key=path.index)))
" )
This way you don't need to escape the slashes for the substitute operator.
这样你就不需要为替代操作符转义斜线了。
回答by Aaron Hall
Linux: Remove redundant paths from $PATH variable
Linux:从 $PATH 变量中删除冗余路径
Linux From Scratch has this function in /etc/profile
Linux From Scratch在 /etc/profile 中有这个功能
$ PATH=$( python -c "import os; path = os.environ['PATH'].split(':'); print(':'.join(sorted(set(path), key=path.index)))" )
This is intended to be used with these functions for adding to the path, so that you don't do it redundantly:
这旨在与这些函数一起使用以添加到路径,这样您就不会重复执行此操作:
$ PATH=$( python -c "
import os
path = os.environ['PATH'].split(':')[::-1]
print(':'.join(sorted(set(path), key=path.index, reverse=True)))
" )
Simple usage is to just give pathremove
the directory path to remove - but keep in mind that it has to match exactly:
简单的用法是给出pathremove
要删除的目录路径 - 但请记住,它必须完全匹配:
#!/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"
This will remove each instance of that directory from your path.
这将从您的路径中删除该目录的每个实例。
If you want the directory in your path, but without the redundancies, you could just use one of the other functions, e.g. - for your specific case:
如果您想要路径中的目录,但没有冗余,您可以只使用其他功能之一,例如 - 对于您的特定情况:
##代码##But, unless readability is the concern, at this point you're better off just doing:
但是,除非考虑可读性,否则此时您最好这样做:
##代码##Would the above work in all shells known to man?
以上是否适用于人类已知的所有外壳?
I would presume the above to work in sh
, dash
, and bash
at least. I would be surprised to learn it doesn't work in csh
, fish', or
ksh`. I doubt it would work in Windows command shell or Powershell.
我会假设上面的工作中sh
,dash
以及bash
至少。我会惊讶地学习这是行不通的csh
,fish', or
ksh`。我怀疑它是否可以在 Windows 命令外壳或 Powershell 中工作。
If you have Python, the following sort of command should do what is directly asked (that is, remove redundant paths):
如果你有 Python,下面的命令应该做直接询问的事情(即删除冗余路径):
##代码##A one-liner (to sidestep multiline issues):
单线(避开多线问题):
##代码##The above removes later redundant paths. To remove earlier redundant paths, use a reversed list's index and reverse it again:
以上删除了后面的冗余路径。要删除较早的冗余路径,请使用反向列表的索引并再次反向:
##代码##回答by Kevin Nathan
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:
如果您只想删除任何重复的路径,我会使用这个脚本,因为我在使用多个 perl5/bin 路径时遇到了问题,所以我写了一段时间:
##代码##And I put it in my ~/.profile at the end. Since I use BASH almost exclusively, I haven't tried it in other shells.
最后我把它放在我的 ~/.profile 中。由于我几乎只使用 BASH,所以我还没有在其他 shell 中尝试过。