Removing a directory from PATH
I’m trying to compile wxWidgets using MingW, and I have cygwin in my path, which seems to conflict. So I would like to remove /d/Programme/cygwin/bin from the PATH variable and I wonder if there is some elegant way to do this. The naive approach would be to echo it to a file, remove it manually and source it, but I bet there is better approach to this.
18 Answers 18
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»). You can 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. However 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, assuming it’s at the end:
PATH=$(echo "$PATH" | sed -e 's/:\/home\/wrong\/dir$//')
So in your case you may use
PATH=$(echo "$PATH" | sed -e 's/:\/d\/Programme\/cygwin\/bin$//')
If the path in question is at the beginning of the PATH variable, you need to match the colon at the end. This is an annoying caveat which complicates easy generic manipulations of PATH variables.
When dealing with so many slashes I prefer to change the regex delimiter / with something like | : PATH=$(echo «$PATH» | sed -e ‘s|:/d/Programme/cygwin/bin$||’) to prevent all the escaping.
This answer explains how to make the pattern more flexible so it works regardless of whether it’s at the end of the path or not: superuser.com/a/1117805 This would yield PATH=$(echo «$PATH» | sed -e ‘s/:\/d\/Programme\/cygwin\/bin\(:\|$\)//’)
Good answer. for those like me that have fat fingers, I would recommend creating a «PRACTICEPATH» to avoid potential grief. Other than that, I think the answer might be improved by adding a «verify» step at the end to make sure «all is well» before you have to find out «the hard way».
export PATH=`echo $PATH | tr «:» «\n» | grep -v «anaconda» | tr «\n» «:»`
That’s the only solution that i can internalize and remember without having to search for this question on SO again
This adds a : at the end of PATH every time the command is used, because grep appends an EOL ( \n ) to its output. Solve this by piping the output of grep through perl -pe ‘chomp if eof’ .
To get rid of the trailing colon, you can also pipe the output to xargs , like so: echo $PATH | tr «:» «\n» | grep -v ‘/usr/local/bin’ | xargs | tr ‘ ‘ ‘:’
directory_to_remove=/d/Programme/cygwin/bin PATH=:$PATH: PATH=$ PATH=$; PATH=$
If you don’t use an intermediate variable, you need to protect the / characters in the directory to remove so that they aren’t treated as the end of the search text.
The first and third line are there to arrange for every component of the search path to be surrounded by : , to avoid special-casing the first and last component. The second line removes the specified component.
A more robust version that eliminates successive directory entries from the path, such as baz:foo:foo:bar :
function path_remove < PATH=":$PATH:" PATH=$PATH=$ PATH=$ PATH=$; PATH=$ >
The second line doubles the colons and the forth line reverts them back to single colons.
Thanks @Gilles, your answer prompted me to come up with my own solution, which only requires three manipulations of PATH rather then four. *8′)
This unfortunately doesn’t eliminate successive directory entries from the path, i.e. baz:foo:foo:bar removing foo becomes baz:foo:bar . This is because the colon on both sides of the pattern matches baz[:foo:]foo:bar and because the last match ended with the colon, it doesn’t pick up with the next :foo: .
After considering other options presented here, and not fully understanding how some of them worked I developed my own path_remove function, which I added to my .bashrc :
function path_remove < # Delete path by parts so we can never accidentally remove sub paths if [ "$PATH" == "$1" ] ; then PATH="" ; fi PATH=$# delete any instances in the middle PATH=$ # delete any instance at the beginning PATH=$ # delete any instance in the at the end >
function path_remove_test <( PATH=$1 path_remove $2 if [ "$PATH" != "$3" ] ; then echo "$1" - "$2" = "$PATH" != "$3" ; fi )>path_remove_test startpath:midpath:endpath startpath midpath:endpath path_remove_test startpath:midpath:endpath midpath startpath:endpath path_remove_test startpath:midpath:endpath endpath startpath:midpath path_remove_test somepath:mypath/mysubpath mypath somepath:mypath/mysubpath path_remove_test path path ""
This ended up pretty close to Gilles’ solution but wrapped up as a bash function which could be easily used on the command line.
It has the advantages that as a bash function it works like a program without needing to be a program on the path, and it doesn’t require any external programs to run, just bash string manipulation.
It appears pretty robust, in particular it doesn’t turn somepath:mypath/mysubpath into somepath/mysubpath :if you run path_remove mypath , which was a problem I had with my previous path_remove function.
An excellent explanation of how bash string manipulation works can be found at the Advanced Bash-Scripting Guide.
How to remove PATH variable on Ubuntu 14.04?
I’ve export PATH=»~/.composer/vendor/bin/lumen» in .bashrc and .bash_profile after export then lumen command not working, Rasel Khan:~$ lumen lumen: command not found But if command type ~/.composer/vendor/bin/lumen in terminal then working, i want only when lumen command type in terminal then exactly same as screenshot. how can i fix this ? see screenshot
4 Answers 4
Your problem will not be solved simply by unsetting PATH, as you’ll still be left without a PATH that includes the necessary system directories. When you set your own PATH, in most cases you will want to append your new entry to the old PATH variable, not replace it entirely, as you have done.
Set your PATH variable back to the system default by typing
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
and then go edit your .bashrc and .bash_profile to have the correct entry, which will be something like
export PATH="$PATH:~/.composer/vendor/bin"
Notice the variable is set to begin with the existing $PATH. This way, you’ll still have all the original system directories in your PATH, and your addition will be on the end. Also note that I removed lumen from the end of your example, because lumen is apparently the name of the binary you are trying to execute, and your PATH should include only directories containing binaries, not the binaries themselves.
thanks, i’ve now default system, but i want to working this comman d export PATH=»$PATH:~/.composer/vendor/bin/lumen , how can i fix this so when command type lumen in terminal and with working
any command not working like ls . etc, i want to remove only this path export PATH=»~/.composer/vendor/bin/lumen» in ` .bashrc` and .bash_profile
See my edited remarks above. I hadn’t noticed earlier that lumen was the name of your binary, not the name of the directory containing your binaries.
Exec this to get your system default:
the PATH stores all the places where the terminal looks for your applications/scripts etc. If you set the PATH to some «unfriendly» directory, the system will not be able to find /bin/sudo and others. You will have to type the whole path like /bin/sudo. The best way to fix this is to open your bash_profile and insert this line: export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games I think changing the profile will work just after the next reboot, so do this and after that use the command export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games to fix it for the current session.
«Protip 😀 :D» if you want to check for your own programs in a directory «/home/username/foo/bin», just add this way to your PATH and you will be able to call the programs stored there just by their names
And for your question above, to unset a variable use unset PATH but this will NOT help you in this case
You need to set your PATH back to what I’ve told you, AND ADD your path. so it should look like export PATH=»/usr/
Bash
Управление переменной среды PATH
Этот файл создается каждый раз, когда запускается новая интерактивная оболочка Bash.
В системах GNU / Linux это обычно файл ~ / .bashrc; в Mac это ~ / .bash_profile или ~ / .profile
Переменная PATH должна быть экспортирована один раз (это делается по умолчанию). После его экспорта он будет экспортирован и любые внесенные в него изменения будут немедленно применены.
Применять изменения:
Чтобы применить изменения к файлу конфигурации Bash, вы должны перезагрузить этот файл в терминале ( source /path/to/bash_config_file )
Добавить путь к переменной среды PATH
Переменная среды PATH обычно определяется в ~ / .bashrc или ~ / .bash_profile или / etc / profile или ~ / .profile или /etc/bash.bashrc (файл конфигурации Bash для дистрибутива)
$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/jdk1.8.0_92/bin:/usr/lib/jvm/jdk1.8.0_92/db/bin:/usr/lib/jvm/jdk1.8.0_92/jre/bin
Теперь, если мы хотим добавить путь (например, ~/bin ) к переменной PATH:
PATH=~/bin:$PATH # or PATH=$PATH:~/bin
Но это изменит PATH только в текущей оболочке (и ее подоболочке). Как только вы выйдете из оболочки, эта модификация исчезнет.
Чтобы сделать его постоянным, нам нужно добавить этот бит кода в файл ~ / .bashrc (или любой другой) и перезагрузить файл.
Если вы запустите следующий код (в терминале), он добавит ~/bin в PATH навсегда:
echo 'PATH=~/bin:$PATH' >> ~/.bashrc && source ~/.bashrc
- echo ‘PATH=~/bin:$PATH’ >> ~/.bashrc добавляет строку PATH=~/bin:$PATH в конце файла ~ / .bashrc (вы можете сделать это с помощью текстового редактора)
- source ~/.bashrc перезагружает файл ~ / .bashrc
path=~/bin # path to be included bashrc=~/.bashrc # bash file to be written and reloaded # run the following code unmodified echo $PATH | grep -q "\(^\|:\)$path\(:\|/\$\)" || echo "PATH=\$PATH:$path" >> "$bashrc"; source "$bashrc"