- Learn How to Set Your $PATH Variables Permanently in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Как изменить переменную Path в Linux
- Как добавить каталог в PATH в Linux
- Что есть $PATH в Linux
- Добавление каталога в ваш $PATH
- Заключение
- How does the path environment variable work in Linux?
- 4 Answers 4
- Linux Mint — adding environment variables permanently [closed]
- 5 Answers 5
Learn How to Set Your $PATH Variables Permanently in Linux
In Linux (also UNIX) $PATH is environment variable, used to tell the shell where to look for executable files. $PATH variable provides great flexibility and security to the Linux systems and it is definitely safe to say that it is one of the most important environment variables.
Programs/scripts that are located within the $PATH’s directory, can be executed directly in your shell, without specifying the full path to them. In this tutorial you are going to learn how to set $PATH variable globally and locally.
First, let’s see your current $PATH’s value. Open a terminal and issue the following command:
The result should be something like this:
The result shows a list of directories separated by colons. You can easily add more directories by editing your user’s shell profile file.
In different shells this can be:
/.bashrc or profile
Korn Shell ->
/.kshrc or .profile
Z shell ->
/.zshrc or .zprofile
Please note that depending on how you are logging to the system in question, different file might be read. Here is what the bash manual says, keep in mind that the files are similar for other shells:
Considering the above, you can add more directories to the $PATH variable by adding the following line to the corresponding file that you will be using:
Of course in the above example, you should change “/path/to/newdir” with the exact path that you wish to set. Once you have modified your .*rc or .*_profile file you will need to call it again using the “source” command.
For example in bash you can do this:
Below, you can see an example of mine $PATH environment on a local computer:
This is actually a good practice to create a local “bin” folder for users where they can place their executable files. Each user will have its separate folder to store his contents. This is also a good measure to keep your system secured.
If you have any questions or difficulties setting your $PATH environment variable, please do not hesitate to submit your questions in the comment section below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Как изменить переменную Path в Linux
wikiHow работает по принципу вики, а это значит, что многие наши статьи написаны несколькими авторами. При создании этой статьи над ее редактированием и улучшением работали авторы-волонтеры.
Количество просмотров этой статьи: 42 610.
Операционные системы обычно используют переменные окружения для определения глобальных настроек или для контроля работы программ. Переменная Path является одной из переменных окружения и постоянно используется без вашего ведома. Переменная хранит список каталогов, в которых расположены исполняемые файлы.
$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/games
$ echo $PATH/home/uzair/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
Источник
Как добавить каталог в PATH в Linux
Но как оболочка узнает, в каких каталогах искать исполняемые программы или оболочка выполняет поиск по всей файловой системе?
Ответ прост. Когда вы вводите команду, оболочка ищет во всех каталогах, указанных в пользовательской переменной $PATH, исполняемый файл с таким именем.
В этой статье показано, как добавить каталоги в вашей переменной $PATH системы Linux.
Что есть $PATH в Linux
Переменная окружающей среды $PATH является двоеточиями список каталогов, сообщает оболочке, какие каталоги для поиска исполняемых файлов.
Чтобы проверить, какие каталоги у вас есть в переменной $PATH, вы можете использовать команду printenv или echo:
Вывод будет выглядеть примерно так:
Если у вас есть два исполняемых файла с одинаковым именем, расположенные в двух разных каталогах, оболочка запустит файл, который находится в каталоге, который стоит первым в $PATH.
Добавление каталога в ваш $PATH
Есть ситуации, когда вы можете захотеть добавить другие каталоги в переменную $PATH. Например, некоторые программы могут быть установлены в разных местах, или вы можете захотеть иметь выделенный каталог для ваших личных записей, но сможете запускать их без указания абсолютного пути к исполняемым файлам. Для этого вам просто нужно добавить каталог в свой $PATH.
Допустим, у вас есть каталог с именем bin, расположенный в вашем домашнем каталоге, в котором вы храните свои сценарии оболочки. Чтобы добавить каталог к вашей переменной $PATH:
Команда export экспортирует измененную переменную в дочерние среды процессов оболочки.
Теперь вы можете запускать ваши скрипты, просто набрав имя исполняемого скрипта без указания полного пути к исполняемому файлу.
Однако это изменение носит временный характер и действует только в текущем сеансе оболочки.
Чтобы сделать изменение постоянным, вам нужно определить переменную $PATH в файлах конфигурации оболочки. В большинстве дистрибутивов Linux при запуске нового сеанса переменные среды считываются из следующих файлов:
- Конфигурационные файлы глобальной оболочки, такие как /etc/environment и /etc/profile. Используйте этот файл, если вы хотите, чтобы новый каталог был добавлен всем системным пользователям $PATH.
- Конфигурационные файлы для отдельных пользовательских оболочек. Например, если вы используете Bash, вы можете установить переменную $PATH в файле
/.bashrc, а если вы используете Zsh – имя файла
В этом примере мы установим переменную в файле
/.bashrc. Откройте файл в текстовом редакторе и добавьте в конце следующую строку:
Сохраните файл и загрузите новое значение $PATH в текущий сеанс оболочки, используя команду source:
Чтобы подтвердить, что каталог был успешно добавлен, напечатайте его значение $PATH, набрав:
Заключение
Добавить новые каталоги в вашу пользовательскую или глобальную переменную $PATH довольно просто. Это позволяет выполнять команды и сценарии, хранящиеся в нестандартных местах, без необходимости вводить полный путь к исполняемому файлу.
Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.
Не стесняйтесь оставлять комментарии, если у вас есть какие-либо вопросы.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
How does the path environment variable work in Linux?
I’m confused how the PATH environment variable works under Linux. I’m a Linux Mint 15 user.
First, I read about editing the /home/.bashrc file and doing a PATH=$PATH:/directory ,
but I also knew about some path stuff managed in /etc/bash.bashrc
and so any software installed in /usr/local/bin would be reachable from anywhere in the shell.
How does the path variable work under Linux and where should it be placed?
4 Answers 4
The basic concept to grasp here is that PATH can be defined in many places. As @demure explains in his answer, PATH=$PATH:/new/dir means add /new_dir to $PATH , it will not clear the original $PATH .
Now, one reason there are many files is intimately connected with the concept of login and non-login shells. See here for a nice summary. The following is from the bash man page (emphasis mine):
When bash is invoked as an interactive login shell, or as a non-interactive shell with the —login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for
/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The —noprofile option may be used when the shell is started to inhibit this behavior.
When you first log into your system, you start a login shell so bash will read the files listed above. Most distributions set a system-wide $PATH (which applies to all users) at /etc/profile and this is where you should make any changes that you want applied to all users. This is what I have on my Debian:
Once you have logged in, when you open a terminal you start an interactive, non-login shell. This is what man bash has to say about those:
So, those files are read every time you open a new terminal. Your filnal $PATH is the combination of the values in all files. In a typical situation, you log in using a graphical log in manager and start a new session. At this pòint your $PATH is whatever was defined in the various profile files. If you open a terminal, then you are in an interactive shell and the different bashrc files are read which may append things to the $PATH .
To summarize, all you really need to know is that you can make changes to your user’s $PATH by editing $HOME/.profile .
Источник
Linux Mint — adding environment variables permanently [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed last year .
I was trying to modify the
/.profile file to add a line to the PATH variable. I added this line:
at the end. I restarted the terminal, but it still did not identify commands in that directory. Does anyone know what I am doing wrong?
5 Answers 5
Try this in the
/.pam_environment in your home folder. If it does not exist then create it:
You will need to log in and out.
Run bash -xl to see which startup files are loaded with your shell. .profile may actually not be read. Otherwise try adding export to your assignment:
Reference about Bash’s startup files: Bash Startup Files
I’m running Linux Mint 18.3 Cinnamon. The changes in file
/.profile got picked up only after I logged out/in from the account. The terminal restart was not enough in my case.
If you edit the .bashrc file,
you will see the next line
/.bash_aliases file in your $HOME folder and add any command you want to be executed when you open the terminal.
You may add an entry to the
Use any editor to access the file. I am using the default Linux Mint Text Editor (xed).
That file is likely to have some entries already. Add a new line to the file and add your entry. For example, I am adding a java binary path which is in the opt folder to the $PATH environment variable:
Or if you want to add a path that is in the user home or something like that, then do like:
Save the file. It should work. If it doesn’t, log out, log back in and try again. If it doesn’t work even after that, then restart and try again and it will work for sure. 🙂
Источник