Linux finding executable 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.

Источник

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?

Читайте также:  Mac os образ установленной системы windows

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:

Источник

Error response from daemon . executable file not found in $PATH» #561

Comments

jonathansberry commented Jan 16, 2019 •

  • This is a bug report
  • This is a feature request
  • I searched existing issues before opening this one

Expected behavior

I expect to be able to run basic containers like hello-world, python, mysql.

Actual behavior

Every container I try to run fails with an executable file not found in $PATH error. It seems like the docker daemon can’t find any executable.

If I try to build a container using a simple docker file:

It fails to find bash to run and create the second layer.

Steps to reproduce the behavior

No one else in my team has this problem

Output of docker version :

Output of docker info :

Additional environment details (AWS, VirtualBox, physical, etc.)
Just running on my local Ubuntu 16.04.5 LTS laptop.

The text was updated successfully, but these errors were encountered:

jonathansberry commented Jan 16, 2019 •

SOLVED — here’s how.

Some one else in my team managed to find this issue lodged with moby:
moby/moby#38174

It reports the same error with one respondant saying:
Yes, you can’t use slave propagation with docker version 18.09 because containerd is running in a different mount namespace.

It reports the fix as being:
I delete «MountFlags=slave» in /lib/systemd/system/docker.service. And «systemctl restart docker», all container running.

I actually found this config param to be set elsewhere in a drop-in config file:
/etc/systemd/system/docker.service.d/docker.conf
After removing the config param, I ran systemctl restart docker and systemctl daemon-reload and had to reboot the machine to get everything working again.

gauravrao08 commented Jan 22, 2019

Hi I am getting error can you plese help me over this.

OCI runtime exec failed: exec failed: container_linux.go:344: starting container process caused «exec: «ping»: executable file not found in $PATH»: unknown

i am running 2 nginx over same network and when i am trying to ping them getting this error.

#docker container exec -it my_new_nginx ping my_nginx_1

cpuguy83 commented Jan 22, 2019

Please check your docker.service configuration.
If you have previously added something like MountPropagation=slave , this would cause issues with Docker 18.09.

You should be able to safely remove any MountPropagation setting.

haydonryan commented Jan 24, 2019

I’m experiencing this on MacOS with Docker engine 18.09.1. My docker advanced daemon setup is:

As far as I know, I haven’t set anything around MountPropagation. Is there somewhere else I should be checking for docker.service config? There’s nothing set outside of credentials in the

cpuguy83 commented Jan 24, 2019

@haydonran under what circumstances are you seeing this behavior?

haydonryan commented Jan 24, 2019

Trying to run docker build after importing an image.

I just realized that I’m posting this under for-linux — apologies. I’ll try an uninstall/reinstall and create a new issue under the for-mac.

DrReblaus commented Feb 15, 2019

Hi @cpuguy83 and @jonathansberry!
I am having the same problem after new installation of docker version CE 18.09.2 on CentOS Linux release 7.6.1810 (Core)

The below run container is the centos image from the docker hub.

Docker Information
centOS information
docker.service file

without any entry for Mountsflag.
docker.service.zip

Thank you for your help

PS: I have also installed a working nextcloud on the same machine as the docker

cpuguy83 commented Feb 15, 2019

This command is trying to run -p 9002/9002 in the centos image, which does not exist.

marcoslneves commented Apr 14, 2019 •

I don’t know why but I was able to run the container by inverting the order of the I was able to execute the container by inverting the order of the -p and container name parameters -p and container name.

docker run -p 8001:8001 container-name:latest

I’m using Engine 18.09.2

My error message:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused «exec: «-p»: executable file not found in $PATH»: unknown.
ERRO[0001] error waiting for container: context canceled

thaJeztah commented Apr 14, 2019

@marcoslneves that’s unrelated; -p is an option for the docker command-line; those options must be put before the container name; everything after the container name is passed to the container as command (so if you put -p after the container name, it will attempt to run -p as command inside the container, which will fail)

thaJeztah commented Apr 14, 2019

Looking at the discussion above, I think the original issue was resolved, so I’m closing this ticket

AbhimanyuG commented Apr 16, 2019 •

Issue still exists in 18.09.5

cpuguy83 commented Apr 16, 2019

See the linked issue. Most likely the issue is you have a custom systemd configuration («MountFlags=slave») and its incompatible with 18.09.

KrishnakNamburi commented Apr 17, 2019 •

The issues persists in centos and 18.9.5 . I donot see any mountflags=slave config in out systemd

KrishnakNamburi commented Apr 17, 2019 •

I found a file /etc/systemd/system/docker.service.d/mountflags-slave.conf
I commented out the MountFlags

systemctl daemon-reload
systemctl restart docker

docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:

  1. The Docker client contacted the Docker daemon.
  2. The Docker daemon pulled the «hello-world» image from the Docker Hub.
    (amd64)
  3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
  4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/

cpuguy83 commented Apr 17, 2019

Yes. The issue with busy errors is fixed and should not need to set the MountFlags option.

In 18.09 specifically, dockerd is no longer responsible for starting/managing containerd (which does all the work to execute the container), instead there is a new service added to systemd.
Because of this, settings like «MountFlags» or «PrivateTmp» will break things due to the fact that containerd will not be able to see mounts created by dockerd. basically these settings cause systemd to create a new mount namespace for each service.

Источник

Читайте также:  Nokia lumia 735 and windows 10
Оцените статью