How to change path variable linux

How to change the PATH variable in Linux

What is a PATH variable

The PATH environment variable stores a colon separated list of locations to look for a command/application when one is run at the command line. For example, when running a command such as ls or vi the system checks all of the directories listed in the PATH (in order from left to right) to find the executable or script the user is attempting to run. This allows for running commands without knowing their location in the file system. Below is an example of PATH variable in Linux systems.

By default, the PATH is already set to look in the following directories:

How to check the valur of PATH variable

To check the current user’s path list, use any of the below commands:

Adding new directory to PATH variable For a specific user

A new directory can be added to a user’s PATH by editing

/.bashrc files in the user’s home directory. For example, the PATH is normally set with lines similar to the following in

To add a new directory to the path (e.g. ‘/new_path’), then change the PATH line by adding it to the end:

Then copy the PATH and EXPORT lines from

/.bashrc to ensure that the path gets set appropriately regardless of how the user logs into the machine. Following those changes the PATH will now include the directory ‘/programs’ the next time the user logs into the system.

Apply changes to current share

To apply the PATH for only the current bash terminal (without logging out), the comand below can be run:

Adding new directory to the PATH variable for all users

The global path can be updated by either:

1. Adding a new file named /etc/profile.d/mypath.sh to be run upon login for all users, containing:

(Note: This method will affect all users (existing users and future users).

2. Editing the file named /etc/skel/.bash_profile in the same way discussed further above in this solution.

  • The files in /etc/skel/ will be copied to any new user’s home directory upon their creation.
  • Note: This method will not have an effect on any existing user accounts.

Источник

Переменная 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 новым, нужно именно добавить (дописать) это новое значение к уже имеющемуся, не забыв о разделителе-двоеточии:

Читайте также:  Как поменять язык linux кнопки

Теперь мы можем убедиться, что в переменной PATH содержится также и имя этой, добавленной нами, папки:

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

В ОС Ubuntu значение переменной PATH содержится в файле /etc/environment, в некоторых других дистрибутивах её также можно найти и в файле /etc/profile. Вы можете открыть файл /etc/environment и вручную дописать туда нужное значение:

sudo vi /etc/environment

Можно поступить и иначе. Содержимое файла .bashrc выполняется при каждом запуске оболочки Bash. Если добавить в конец файла команду export, то для каждой загружаемой оболочки будет автоматически выполняться добавление имени требуемой папки в переменную PATH, но только для текущего пользователя:

Выводы

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

Источник

How to set your $PATH variable in Linux

Telling your Linux shell where to look for executable files is easy, and something everyone should be able to do.

Subscribe now

Get the highlights in your inbox every week.

Being able to edit your $PATH is an important skill for any beginning POSIX user, whether you use Linux, BSD, or macOS.

When you type a command into the command prompt in Linux, or in other Linux-like operating systems, all you’re doing is telling it to run a program. Even simple commands, like ls, mkdir, rm, and others are just small programs that usually live inside a directory on your computer called /usr/bin. There are other places on your system that commonly hold executable programs as well; some common ones include /usr/local/bin, /usr/local/sbin, and /usr/sbin. Which programs live where, and why, is beyond the scope of this article, but know that an executable program can live practically anywhere on your computer: it doesn’t have to be limited to one of these directories.

When you type a command into your Linux shell, it doesn’t look in every directory to see if there’s a program by that name. It only looks to the ones you specify. How does it know to look in the directories mentioned above? It’s simple: They are a part of an environment variable, called $PATH, which your shell checks in order to know where to look.

View your PATH

Sometimes, you may wish to install programs into other locations on your computer, but be able to execute them easily without specifying their exact location. You can do this easily by adding a directory to your $PATH. To see what’s in your $PATH right now, type this into a terminal:

You’ll probably see the directories mentioned above, as well as perhaps some others, and they are all separated by colons. Now let’s add another directory to the list.

Set your PATH

Let’s say you wrote a little shell script called hello.sh and have it located in a directory called /place/with/the/file. This script provides some useful function to all of the files in your current directory, that you’d like to be able to execute no matter what directory you’re in.

Simply add /place/with/the/file to the $PATH variable with the following command:

You should now be able to execute the script anywhere on your system by just typing in its name, without having to include the full path as you type it.

Set your PATH permanently

But what happens if you restart your computer or create a new terminal instance? Your addition to the path is gone! This is by design. The variable $PATH is set by your shell every time it launches, but you can set it so that it always includes your new path with every new shell you open. The exact way to do this depends on which shell you’re running.

Not sure which shell you’re running? If you’re using pretty much any common Linux distribution, and haven’t changed the defaults, chances are you’re running Bash. But you can confirm this with a simple command:

That’s the «echo» command followed by a dollar sign ($) and a zero. $0 represents the zeroth segment of a command (in the command echo $0, the word «echo» therefore maps to $1), or in other words, the thing running your command. Usually this is the Bash shell, although there are others, including Dash, Zsh, Tcsh, Ksh, and Fish.

Читайте также:  Рекомендуемые системные требования для windows 10 64 bit

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called

/.profile. The difference between these files is (primarily) when they get read by the shell. If you’re not sure where to put it,

/.bashrc is a good choice.

For other shells, you’ll want to find the appropriate place to set a configuration at start time; ksh configuration is typically found in

/.zshrc. Check your shell’s documentation to find what file it uses.

This is a simple answer, and there are more quirks and details worth learning. Like most everything in Linux, there is more than one way to do things, and you may find other answers which better meet the needs of your situation or the peculiarities of your Linux distribution. Happy hacking, and good luck, wherever your $PATH may take you.

This article was originally published in June 2017 and has been updated with additional information by the editor.

Источник

UNIX / Linux: Set your PATH Variable Using set or export Command

H ow do I add a new path to $PATH variable under Linux and UNIX like operating system? What is my path, and how do I set or modify it using csh/tcsh or bash/ksh/sh shell?

The PATH is an environment variable. It is a colon delimited list of directories that your shell searches through when you enter a command. All executables are kept in different directories on the Linux and Unix like operating systems.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 5m

Finding out your current path

To find out what your current path setting, type the following command at shell prompt. Open the Terminal and then enter:

How do I modify my path?

To modify your path edit $PATH variable as per your shell. The syntax for setting path under UNIX / Linux dependent upon your login shell.

Bash, Sh, Ksh shell syntax to modify $PATH

If you are using bash, sh, or ksh, at the shell prompt, type:

Please feel free to replace /path/to/dir1 with the directory you want the shell to search.

Tcsh or csh shell syntax to modify $PATH

If you are using tcsh or csh, shell enter:

Please feel free to replace /path/to/dir1 with the directory you want the shell to search.

Examples

In this example add /usr/local/bin to your path under BASH/ksh/sh shell, enter:

To make these changes permanent, add the commands described above to the end of your

/.profile file for sh and ksh shell, or

/.bash_profile file for bash shell:

KSH/sh shell user try:

In this final example add /usr/local/bin/ and /scripts/admin/ to your path under csh / tcsh shell, enter:

To make these changes permanent, add the commands described above to the end of your

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

To verify new path settings, enter:
$ echo $PATH

See also

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

I am a newbie on Linux.

I would like to ask if I can include an environment variable (e.g. ARCHIVES) that points to a directory (e.g. EXPORT ARCHIVES=/some/path/directory) to the .bash_profile, so that I dont do exporting all the time, everytime I need to use the directory?

How to set the CLASSPATH??

Or add as follows to your .bashrc file:
“echo ‘export PATH=$PATH:/usr/local/bin’ >>

Isn’t echo ” ‘PATH=$PATH:/usr/local/bin’ >>

/.bashrc ” a better idea?

how can I remove a path variable??

Hi,
To remove a path, go to”File System”. Open
/etc folder and edit (that is, remove )the path from the ‘environment’ text file. You can edit using the sudo command. Following are the commands.
cd

cd etc
sudo gedit environment

After removing the path from the “environment” file, save and restart the machine

Hi,
There was one mistake. It is “cd /”, not “cd


To remove a path, go to”File System”. Open
/etc folder and edit (that is, remove )the path from the ‘environment’ text file. You can edit using the sudo command. Following are the commands.
cd /
cd etc
sudo gedit environment

After removing the path from the “environment” file, save and restart the machine

To add a PATH for any user with sh or bash shell permanantly use the following steps.

1. Create a new file .profile in root(/) directory.
2. Add the following lines into it
PATH= path to enter
export PATH
3.save the file
4.exit and login to server again
5.check using echo $PATH

IT will work. Please let me know if tou have any queries on this .

The above one is only for root user

When I run my program I get this result:
terminate called after throwing an instance of ‘std::logic_error’
what(): basic_string::_S_construct NULL not valid
Aborted

Is this a result of having the wrong environment variable on my path or what. The program compiles without any errors. This is happening on Ubuntu (Linux, OS 10.0)

Could any one explain me about the functionality of command in shell script
set -xv
. /opt/app/etl/bin/profile.ksh
. `dirname $0`/env.cfg

Print input commands and their arguments as they are executed –> when you use set -xv

Hi there, thanks fo the article!

FYI, I just tried the syntax above for a tcsh but it didn’t work.
This works:

(Include this line directly in your .cshrc file. This example adds a dir called

/bin and your current dir to the previously existing PATH)

(Or, if you don’t want to open and edit your

/.cshrc file, type this in a teminal:)

Thanks for the heads up. The faq has been updated with correct syntax. FYI, the syntax setenv PATH $:$/bin:. can be updated using the following syntax too:

Appreciate your post.

it helps me lots thanks………….

Hi :
I am new to linux.
May I ask how to convert this bash to tcsh?

Best Regards,
McGrady

why would this code be on my computer in a install file with along with macports pubkey and several other files.

SET doesn’t seem to do anything.
PATH as a variable name is case sensitive by me, but in this tut, this gets ignored.
Very bad. Didn’t helped me at all.

by mistake i changed defaults PATH ,how can i get default PATH from command line
i can’t even vi that hiden files

I have a machine that is running on kernel 2.6.32-504.16.2.el6.x86_64, I want to build a custom kernel using the same kernel on the same machine, but when I run make menuconfig, I get the following error

*** Unable to find the ncurses libraries or the
*** required header files.
*** ‘make menuconfig’ requires the ncurses libraries.
***
*** Install ncurses (ncurses-devel) and try again.
***
make[1]: *** [scripts/kconfig/dochecklxdialog] Error 1
make: *** [menuconfig] Error 2

I have the ncurses installed already in /lib64 and modified my PATH to point to /lib64, but I still get the same error, it looks like that it can not be found. does anyone have an idea why this is not working?

Install “ncurses-devel” package and try again.

Источник

Читайте также:  Google chrome или firefox linux
Оцените статью