- How to permanently set $PATH on Linux/Unix [closed]
- Background
- 24 Answers 24
- System wide
- User session
- Notes
- Man pages
- How to Permanently Set $PATH in Linux
- What is a $PATH Variable in Linux
- Check $PATH Variables in Linux
- Add a Directory to PATH Variable Linux
- Permanently Set $PATH for All Users
- Set PATH Variable in /etc/environment File
- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
How to permanently set $PATH on Linux/Unix [closed]
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Background
This works, however each time I exit the terminal and start a new terminal instance, this path is lost, and I need to run the export command again. How can I do it so this will be set permanently?
If you are on a mac, then bashrc works fine, no need to continuously source ~/.profile for the terminal to read from the environment variables
24 Answers 24
You need to add it to your ~/.profile or ~/.bashrc file.
Depending on what you’re doing, you also may want to symlink to binaries:
cd /usr/bin sudo ln -s /path/to/binary binary-name
Note that this will not automatically update your path for the remainder of the session. To do this, you should run:
source ~/.profile or source ~/.bashrc
A couple of questions. 1) Shouldn’t there be a colon between $PATH and /usr/bin . 2) Should /usr/bin even be there. 3) Shouldn’t you rather use /usr/local/bin ?
Please note: it’s often considered a security hole to leave a trailing colon at the end of your bash PATH because it makes it so that bash looks in the current directory if it can’t find the executable it’s looking for. Users who find this post looking for more information should be advised of this.
@AdamRobertson It is unsafe- consider the scenario when you unpack a tarball, then cd to the directory you unpacked it in, then run ls —and then realize that the tarball had a malicious program called ls in it.
I think I significantly improved the quality of this answer, and addressed a few issues which other users brought up. Every path export, or every command which adjusts the path, should always make sure to separate an existing path with a colon. Leading or trailing colons should never be used, and the current directory should never be in the path.
There are multiple ways to do it. The actual solution depends on the purpose.
The variable values are usually stored in either a list of assignments or a shell script that is run at the start of the system or user session. In case of the shell script you must use a specific shell syntax and export or set commands.
System wide
- /etc/environment List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME . Used by PAM and systemd.
- /etc/environment.d/*.conf List of unique assignments. Allows references. Perfect for adding system-wide directories like /usr/local/something/bin to PATH variable or defining JAVA_HOME . The configuration can be split into multiple files, usually one per each tool (Java, Go, and Node.js). Used by systemd that by design do not pass those values to user login shells.
- /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window System. It is a good choice for PATH entries that are valid for every user like /usr/local/something/bin . The file is included by other script so use POSIX shell syntax not the syntax of your user shell.
- /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells in login mode.
- /etc/.rc . Shell script. This is a poor choice because it is single shell specific. Used in non-login mode.
User session
- ~/.pam_environment . List of unique assignments, no references allowed. Loaded by PAM at the start of every user session irrelevant if it is an X Window System session or shell. You cannot reference other variables including HOME or PATH so it has limited use. Used by PAM.
- ~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to every X application. Perfect choice for extending PATH with values such as ~/bin or ~/go/bin or defining user specific GOPATH or NPM_HOME . The file is included by other script so use POSIX shell syntax not the syntax of your user shell. Your graphical text editor or IDE started by shortcut will see those values.
- ~/.profile , ~/._profile , ~/._login Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for shell-only systems. Used by shells in login mode.
- ~/.rc . Shell script. This is a poor choice because it is single shell specific. Used by shells in non-login mode.
Notes
GNOME on Wayland starts a user login shell to get the environment. It effectively uses the login shell configurations ~/.profile , ~/._profile , ~/._login files.
Man pages
How to Permanently Set $PATH in Linux
Unlocking the full potential of your Linux system involves understanding the importance of the $PATH variable, which serves as a roadmap for your operating system to locate and execute commands swiftly and effortlessly. However, if you find yourself repeatedly setting the $PATH every time you log in or reboot, it is time to learn how to permanently configure it.
In this comprehensive guide, we will walk you through the step-by-step process of setting the $PATH variable in Linux, ensuring that your customizations persist across sessions.
What is a $PATH Variable in Linux
The $PATH variable is a fundamental part of the Linux operating system, acting as a reference to locate executable files. It consists of a list of directories separated by colons (:) , with the system searching for commands in these directories when they are executed. Understanding the importance of the $PATH variable is crucial to effectively manage your command-line experience.
There are multiple approaches to permanently setting the $PATH variable in Linux and the two most common methods involve:
Each method has its advantages and disadvantages, so choose the one that best suits your needs. The PATH variable can also be set on a per-user basis or system-wide for all user accounts.
Check $PATH Variables in Linux
You can see your $PATH variables by running the following echo command:
Add a Directory to PATH Variable Linux
To temporarily add a directory, for example, /opt/sysadmin/scripts to your path, you can run the following command:
$ PATH=$PATH:/opt/sysadmin/scripts $ echo $PATH
One way to permanently set the $PATH variable is by modifying shell configuration files, such as .bashrc or .bash_profile . These files are executed each time you start a new shell session.
$ nano ~/.bashrc OR $ vim ~/.bashrc
Locate the line that begins with «export PATH attachment_8239″ aria-describedby=»caption-attachment-8239″ style=»width: 831px» > The .bashrc File in Linux
If you are unable to find this line, you can add it manually inside the file at the bottom of the page. As an example, I am adding the /opt/sysadmin/scripts directory path to my PATH using the command given below:
export PATH="$PATH: /opt/sysadmin/scripts"
To apply the changes, either open a new terminal or run the following command:
Note: The above method only works for user accounts.
Permanently Set $PATH for All Users
To permanently set system PATH for all users on the system, append the following lines at the end of the /etc/profile file. On some Linux distros, you can also use the /etc/bash.bashrc file (if it exists) but it should be sourced in /etc/profile for changes in it to work.
PATH="$PATH:/opt/sysadmin/scripts" export $PATH OR $export PATH="$PATH:/opt/sysadmin/scripts"
Alternatively, instead of making changes directly in the /etc/profile (which is not recommended), you can create a script (ending with the .sh extension) under the directory /etc/profile.d (if it exists) and make the changes in that script.
$ sudo vim /etc/profile.d/set_system_path.sh
Append the following line in it:
export PATH="$PATH:/opt/sysadmin/scripts"
Next, source the ~/.bashrc or /etc/profile or /etc/bash.bashrc (depending on the one you used), for the changes to take effect.
$ source ~/.bashrc OR $ source /etc/profile OR $ source /etc/bash.bashrc
Then confirm that your PATH has been set correctly:
$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/sysadmin/scripts:/opt/sysadmin/scripts
Set PATH Variable in /etc/environment File
Another approach to permanently setting the $PATH a variable is by using environment-specific files. Two common files used for this purpose are /etc/environment and /etc/profile.d/.
Next, locate the line that begins with «PATH /opt/sysadmin/scripts:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/>
To apply the changes, reboot your system or run the following command:
After making modifications to the $PATH variable, it’s crucial to verify that the changes have taken effect.
This will display the updated $PATH variable, including the directories you added. Ensure that the desired directories are now part of the $PATH variable.
Conclusion
To make the most of your Linux system, it’s a must for you to understand the $PATH variable that acts like a map and helps your computer find and run commands quickly.
If you are tired of setting $PATH every time you log in or restart your computer, better to set it permanently using the step-by-step guidelines presented in the above article.
If you have managed to do this process, you will have a better command-line experience on your Linux system.
Переменная PATH в Linux
Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.
Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.
Переменная PATH в Linux
Для того, чтобы посмотреть содержимое переменной PATH в Linux, выполните в терминале команду:
На экране появится перечень папок, разделённых двоеточием. Алгоритм поиска пути к требуемой программе при её запуске довольно прост. Сначала ОС ищет исполняемый файл с заданным именем в текущей папке. Если находит, запускает на выполнение, если нет, проверяет каталоги, перечисленные в переменной PATH, в установленном там порядке. Таким образом, добавив свои папки к содержимому этой переменной, вы добавляете новые места размещения исполняемых и связанных с ними файлов.
Для того, чтобы добавить новый путь к переменной PATH, можно воспользоваться командой export. Например, давайте добавим к значению переменной PATH папку/opt/local/bin. Для того, чтобы не перезаписать имеющееся значение переменной PATH новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:
Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:
Вы уже знаете как в Linux добавить имя требуемой папки в переменную PATH, но есть одна проблема — после перезагрузки компьютера или открытия нового сеанса терминала все изменения пропадут, ваша переменная PATH будет иметь то же значение, что и раньше. Для того, чтобы этого не произошло, нужно закрепить новое текущее значение переменной PATH в конфигурационном системном файле.
В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:
Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:
Выводы
В этой статье мы рассмотрели вопрос о том, зачем нужна переменная окружения PATH в Linux и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.