How to get linux path

Переменная 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 и вручную дописать туда нужное значение:

sudo vi /etc/environment

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

Выводы

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

Источник

How to show the full path of a file or directory in the terminal?

I need to know how the directory name in order to type it out in the terminal. How do I access the names of directories?

Windows Explorer used to have a title bar with the full path. Can someone please help me figure out how to see the full path of a certain file?

3 Answers 3

If you are using nautilus to browse your files, you can toggle the navigation bar by pressing Ctrl + L .

If you are using the terminal, just use pwd to know the absolute path of your current location.

To display the full path of a file in the terminal just drag the file’s icon into the terminal, and the full path of the file will be displayed enclosed by two apostrophes (single quotation mark characters). It’s that simple.

Читайте также:  Xubuntu или linux lite

In Ubuntu 20.04 and later drag and drop of files or directories doesn’t work from the desktop, but does work in other locations including dragging from the desktop in Files file manager.

find can do this quite handily from the terminal. Here’s an example in which I’m looking for the full path of the file Taxes-2013.pdf:

sudo find / -name Taxes-2013.pdf

Provides the output:

I’m using sudo so that I can avoid all the permission denied output that I would otherwise get with find when searching from the root of the tree.

If you just want the pathname and want the filename stripped off you can use

sudo find / -name Taxes-2013.pdf | xargs -n1 dirname

Note: If you are in the habit of putting spaces in names this is relevant to you.

Источник

How to get full path name of a Linux command

I want to find out the file path of commands in Linux e.g., ls has file path as /bin/ls . How can I find out the exact path of some commands?

5 Answers 5

As pointed out, which

would do it. You could also try:

This will list all the paths that contains progName . I.e whereis -b gcc on my machine returns:

you can use which , it give you path of command:

you can use type :

You can use the which command. In case of a command in your $PATH it will show you the full path:

And it will also show details about aliases:

Yes you can find it with which command

You did not specify, which shell you are going to use, but I strongly recommend using which , as it does not necessarily do, what you expect. Here two examples, where the result possibly is not what you expect:

(1) Example with bash, and the command echo :

would output /usr/bin/echo , but if you use the echo command in your bash script, /usr/bin/echo is not executed. Instead, the builtin command echo is executed, which is similar, but not identical in behaviour.

(2) Example with zsh, and the command which :

would output the message which: shell built-in command (which is correct, but certainly not a file path, as you requested), while

would output the file path /usr/bin/which , but (as in the bash example) this is not what’s getting executed when you just type which .

There are cases, when you know for sure (because you know your application), that which will produce the right result, but beware that as soon as builtin-commands, aliases and shell functions are involved, you need first to decide how you want to handle those cases, and then choose the appropriate tools depending on the kind of shell which you are using.

Источник

How do I get the path of a process in Unix / Linux

In Windows environment there is an API to obtain the path which is running a process. Is there something similar in Unix / Linux?

Or is there some other way to do that in these environments?

11 Answers 11

On Linux, the symlink /proc/

/exe has the path of the executable. Use the command readlink -f /proc/

/exe to get the value.

On AIX, this file does not exist. You could compare cksum and cksum /proc/

You can find the exe easily by these ways, just try it yourself.

gave me the location of the symbolic link so I could find the logs and stop the process in proper way.

| grep -m 1 txt , as the required process path info seems to be in the first line with txt , and not in the cwd line? (Applies on macOS and Ubuntu as of date of posting.)

A little bit late, but all the answers were specific to linux.

If you need also unix, then you need this:

EDITED: Fixed the bug reported by Mark lakata.

Читайте также:  Jbl quantum engine linux

Replace 786 with your PID or process name.

This command will fetch the process path from where it is executing.

In Linux every process has its own folder in /proc . So you could use getpid() to get the pid of the running process and then join it with the path /proc to get the folder you hopefully need.

Here’s a short example in Python:

Here’s the example in ANSI C as well:

Compile it with:

There’s no «guaranteed to work anywhere» method.

Step 1 is to check argv[0], if the program was started by its full path, this would (usually) have the full path. If it was started by a relative path, the same holds (though this requires getting teh current working directory, using getcwd().

Step 2, if none of the above holds, is to get the name of the program, then get the name of the program from argv[0], then get the user’s PATH from the environment and go through that to see if there’s a suitable executable binary with the same name.

Note that argv[0] is set by the process that execs the program, so it is not 100% reliable.

The below command search for the name of the process in the running process list,and redirect the pid to pwdx command to find the location of the process.

Replace «abc» with your specific pattern.

Alternatively, if you could configure it as a function in .bashrc, you may find in handy to use if you need this to be used frequently.

Hope this helps someone sometime.

thanks : Kiwy
with AIX:

You can also get the path on GNU/Linux with (not thoroughly tested):

If you want the directory of the executable for perhaps changing the working directory to the process’s directory (for media/data/etc), you need to drop everything after the last /:

Источник

Display or print UNIX / Linux path

I am a new Linux or Unix system user and I am using a Debian Linux VPS. How do I print current path settings under BASH or sh or ksh shell?

In Linux or Unix-like file systems, the human-readable address of a resource is defined by PATH shell variable. On Unix / Linux like operating systems, (as well as on DOS / Windows and its descendants), PATH is an environment variable listing a set of paths to directories where executable may be found. This page explains how to print path variable using various commands under Linux and Unix-like systems.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux, Unix, or macOS terminal app
Est. reading time 2 minutes

Display current PATH in Linux

Use the echo command as follows:
echo «$PATH»
Here is my settings from Debian Linux system:

You can use the printf command as well to show the current PATH settings:
$ printf «%s\n» $PATH
Here is my settings from macOS/macOS X Unix desktop:

What is a PATH in Linux or Unix?

A PATH is nothing but the search path for commands. It is a colon-separated list of directories in which the shell looks for commands.

How to modify current PATH

Use the export command to add /opt/games to PATH, enter:
export PATH=$PATH:/opt/games
To format your PATH variable for easy viewing, add following code to your bash startup file (such as

  • 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

Now just run path:
$ path
Here is what I see on CentOS/RHEL/Fedora Linux:

Another option is to run the following command:
echo «$PATH» | tr «:» «\n» | nl

Fig.01: Printing $PATH on Linux or Unix-like system

Summing up

The default shell path ( $PATH variable) is system-dependent, and is set by the administrator who installs bash or ksh or any other shell. However, developers and other Linux and Unix system users can set up their own path using the export command under bash/sh/ksh.

Setting up PATH permanently

Users can edit the

/.profile to set up their path as follows for bash:

Printing PATH in Linux or Unix

Now run:
echo «$PATH»
printf «%s\n», $PATH

How to Checking Path in Unix and Linux

🐧 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.

accepts an optional argument that is the name of a path-like variable.

Hi,
I did not get either of those path() working. I assume my version of unix does not recognize IFS when applying printf. But this works:

echo $PATH | sed ‘s/\:/\n/g’ | sort

Thanks for that, Pekka. I started using zsh, which has the same problem you described. The original solution works wonderfully in bash, but yours works in zsh.

Ugghh curly quotes. Could not copy and paste.

I am using Zshell, Prezto, OSX. The sed command replaces the : with an n

To get one path per line I used:

Hello Sir;
I am trying to run a program on a cluster and every time I run the program I have this message: mpiexec was unable to launch the specified application as it could not find an executable. ”
so I am suggesting that the program is not recognize the mpixec path. so I need to add the MPI path in my working directory.
my question is how to set this up?

hola necesito decargar un editor ok lo descargo en superusuario y cuando esta descargando me dice q no puede continuar … me aparece esto : dpkg: aviso: `ldconfig’ no se ha encontrado en el PATH o no es ejecutable.
dpkg: aviso: `start-stop-daemon’ no se ha encontrado en el PATH o no es ejecutable.
dpkg: error: 2 expected programs not found in PATH or not executable.
Note: root’s PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin.
E: Sub-process /usr/bin/dpkg returned an error code (2)
Un paquete no se pudo instalar. Tratando de recuperarlo:
dpkg: aviso: `ldconfig’ no se ha encontrado en el PATH o no es ejecutable.
dpkg: aviso: `start-stop-daemon’ no se ha encontrado en el PATH o no es ejecutable.
dpkg: error: 2 expected programs not found in PATH or not executable.
Note: root’s PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin.
help me..

In below code:
Node=/liferay-portal-5.2.0/jboss-tomcat-4.2.3/server/node_portal
export jboss=$Node/../..
echo $jboss

But I need Output as :

Please help me out in this.

How can I make PATH easily to view when I just execute the script? Thanks

You can search/replace within variables as you expand them.
The following replaces ‘:’ with newlines while expanding $PATH, so it’s done without using external commands:

Источник

Читайте также:  Ограничение время работы компьютера windows
Оцените статью