Updating path in linux

How can I edit the $PATH on linux?

To permanently store your path, you have a few options.

I suggest you read the Ubuntu community wiki on Environment Variables but the short answer is the best place is ~/.profile for your per-user PATH setting or /etc/profile for global settings.

Change PATH:

export PATH=$PATH:/your/new/path/here 
export PATH=:/your/new/path/here:/another/new/path/here 

It is important to note that there are many occasions your profile is not run (such as when a script is run by cron). If you need a specific path to be set in PATH, a script must set that path. That said, scripts should never rely on anything being in their paths and should always use absolute paths, anything else is a security issue.

Reader, if you want to edit the $PATH on Linux, not just add a path to it, see the answer to superuser.com/questions/1353497/removing-directories-from-path instead.

PATH=$PATH:newPath1:newPAth2 export PATH 

It depends on the shell you’re using. On Solaris (I know the question is about Linux) one of the shells (can’t remember which one off the top of my head) requires that you do the export separately from setting the value in a script. So I’ve just gotten into the habit of doing it on 2 lines.

You can also put this in the global environment:

sudo emacs /etc/environment 

Append to the entries already in your path

It has already been answered on how to do that, but I’d like to give you a little tip. Here is whatI do:

I have a directory called .bash.d in my $HOME and within that I keep a set of shell scripts that do stuff to my environment (for instance setup maven correctly, modify the path, set my prompt etc.). I keep this under version control by using git, which makes it easy to go back to a working version of your env, if you screw something up badly. To get all the modifications, I simply source all files in that dir at the end of my .bashrc like this:

for i in $HOME/.bash.d/*; do source $i; done unset i 

This gives you a very flexible environment that you can easily modify and restore + you are able to export it to other machines just by using git.

Источник

Переменная PATH в Linux

Когда вы запускаете программу из терминала или скрипта, то обычно пишете только имя файла программы. Однако, ОС Linux спроектирована так, что исполняемые и связанные с ними файлы программ распределяются по различным специализированным каталогам. Например, библиотеки устанавливаются в /lib или /usr/lib, конфигурационные файлы в /etc, а исполняемые файлы в /sbin/, /usr/bin или /bin.

Таких местоположений несколько. Откуда операционная система знает где искать требуемую программу или её компонент? Всё просто — для этого используется переменная PATH. Эта переменная позволяет существенно сократить длину набираемых команд в терминале или в скрипте, освобождая от необходимости каждый раз указывать полные пути к требуемым файлам. В этой статье мы разберёмся зачем нужна переменная PATH Linux, а также как добавить к её значению имена своих пользовательских каталогов.

Читайте также:  Определить расширение файла 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.

Источник

What is this $PATH in Linux and how to modify it

Yes, you can change it — for example add to the $PATH folder with your custom scripts.

So: if your scripts are in /usr/local/myscripts to execute them you will have to type in a full path to the script: /usr/local/myscripts/myscript.sh After changing your $PATH variable you can just type in myscript.sh to execute script.

Here is an example of $PATH from RHEL:

Читайте также:  Mdk3 kali linux установка

To change your $PATH you have to either edit ~/.profile (or ~/.bash_profile ) for user or global $PATH setting in /etc/profile .

One of the consequences of having inaccurate $PATH variables is that shell will not be able to find and execute programs without a full $PATH .

Oh my God, you clarified it all for me by your statement —> «So: if your scripts are in /usr/local/myscripts to execute them you will have to type in a full path to the script: /usr/local/myscripts/myscript.sh After changing your $PATH variable you can just type in myscript.sh to execute script.» Thanks a lot

@ruggedbuteducated just bash commands which are executed after you log in. Please look into man bash and search for bashrc.

Firstly, you are correct in your statement of what $PATH does. If you were to break it somehow (as per your third point), you will have to manually type in /usr/bin/xyz if you want to run a program in /usr/bin from the terminal. Depending on how individual programs work, this might break some programs that invoke other ones, as they will expect to just be able to run ls or something.

So if you were to play around with $PATH, I would suggest saving it somewhere first. Use the command line instruction

echo $PATH > someRandomFile.txt 

to save it in someRandomFile.txt

You can change $PATH using the export command. So

HOWEVER, this will completely replace $PATH with someNewPath. Since items in path are separated by a «:», you can add items to it (best not to remove, see above) by executing

The fact that it is an environmental variable means that programs can find out its value, ie it is something that is set about the environment that the program is running in. Other environmental variables include things like the current directory and the address of the current proxy.

Источник

How To View and Update the Linux PATH Environment Variable

How To View and Update the Linux PATH Environment Variable

After installing a command-line program, you may only be able to run it in the same directory as the program. You can run a command-line program from any directory with the help of an environment variable called PATH .

The PATH variable contains a list of directories the system checks before running a command. Updating the PATH variable will enable you to run any executables found in the directories mentioned in PATH from any directory without typing the absolute file path.

For example, instead of typing the following to run a Python program:

Because the /usr/bin directory is included in the PATH variable, you can type this instead:

The directories are listed in priority order, so the ones that will be checked first are mentioned first.

In this tutorial, you will view the PATH variable and update its value.

Prerequisites

For an overview of environment variables, refer to the How To Read and Set Environmental and Shell Variables on Linux article.

Step 1 — Viewing the PATH Variable

You can view the PATH variable with the following command:

Читайте также:  Dell vostro 3500 linux

An unchanged PATH may look something like this (file paths may differ slightly depending on your system):

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

Some directories are mentioned by default, and each directory in PATH is separated with a colon : . The system checks these directories from left to right when running a program.

When a command-line program is not installed in any of the mentioned directories, you may need to add the directory of that program to PATH .

Step 2 — Adding a Directory to the PATH Environment Variable

A directory can be added to PATH in two ways: at the start or the end of a path.

Adding a directory ( /the/file/path for example) to the start of PATH will mean it is checked first:

Adding a directory to the end of PATH means it will be checked after all other directories:

Multiple directories can be added to PATH at once by adding a colon : between the directories:

Once the export command is executed, you can view the PATH variable to see the changes:

You will see an output like this:

Output
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games:/the/file/path

This method will only work for the current shell session. Once you exit the current session and start a new one, the PATH variable will reset to its default value and no longer contain the directory you added. For the PATH to persist across different shell sessions, it has to be stored in a file.

Step 3 — Permanently Adding a Directory to the PATH Variable

In this step, you will add a directory permanently in the shell configuration file, which is ~/.bashrc if you’re using a bash shell or ~/.zshrc if you’re using a zsh shell. This tutorial will use ~/.bashrc as an example.

First, open the ~/.bashrc file:

The ~/.bashrc file will have existing data, which you will not modify. At the bottom of the file, add the export command with your new directory:

Use the methods described in the prior section to clarify whether you want the new directory to be checked first or last in the PATH .

Save and close the file. The changes to the PATH variable will be made once a new shell session is started. To apply the changes to the current session, use the source command:

You can add new directories in the future by opening this file and appending directories separated by a colon : to the existing export command.

Conclusion

The PATH environment variable is a crucial aspect of command-line use. It enables you to run command-line programs, such as echo and python3 , from any directory without typing the full path. In cases where adding the directory to PATH isn’t part of the installation process, this tutorial provides the required steps. For more on environmental variables, see How To Read and Set Environmental and Shell Variables on Linux.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью
Adblock
detector