- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
- How to get full path name of a Linux command
- 5 Answers 5
- Путь к файлу в Linux
- Пути файлов в Linux
- Выводы
- Getting the Absolute (Full) and Relative Path In Linux
- FileSystem Paths
- Relative Paths
- Example
- Absolute Paths
- Example
- Paths and Hard / Soft Links (symlinks)
- Brad Morton
- How can I generate a list of files with their absolute path in Linux?
- 26 Answers 26
Переменная 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 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.
Источник
Путь к файлу в Linux
Все файлы в Linux имеют определенный адрес в файловой системе, с помощью которого мы можем получить к ним доступ с помощью файлового менеджера или консольных утилит. Это довольно простая тема, но у многих новичков с этим возникают трудности.
В сегодняшней небольшой заметке мы рассмотрим что такое путь к файлу Linux, каким он может быть, как правильно его писать и многое другое. Если раньше у вас возникали с этим трудности, то после прочтения статьи все станет полностью понятно.
Пути файлов в Linux
Файловая система Linux очень сильно отличается от Windows. Мы не будем рассматривать ее структуру, это было сделано ранее. Мы сосредоточимся на работе с файлами.
Самое главное отличие, в том что адрес файла начинается не с диска, например, C:\ или D:\ как это происходит в Windows, а с корня, корневого системного каталога, к которому подключены все другие. Его адрес — /. И тут нужно сказать про адреса. Пути файлов linux используют прямой слеш «/» для разделения каталогов в адресе, и это отличается от того, что вы привыкли видеть в Windows — \.
Например, если в Windows полный путь к файлу на рабочем столе выглядел C:\Users\Sergiy\Desktop\ то в путь файла в linux будет просто /home/sergiy/desktop/. С этим пока все просто и понятно. Но проблемы возникают дальше.
В операционной системе Linux может быть несколько видов путей к файлу. Давайте рассмотрим какие бывают пути в linux:
- Полный, абсолютный путь linux от корня файловой системы — этот путь вы уже видели в примере выше, он начинается от корня «/» и описывает весь путь к файлу;
- Относительный путь linux — это путь к файлу относительно текущей папки, такие пути часто вызывают путаницу.
- Путь относительно домашний папки текущего пользователя. — путь в файловой системе, только не от корня, а от папки текущего пользователя.
Рассмотрим теперь подробнее как выглядят эти пути в linux, а также разберем несколько примеров, чтобы было окончательно понятно. Для демонстрации будем пользоваться утилитой ls, которая предназначена для просмотра содержимого каталогов.
Например, у нас есть такой каталог в домашней папке с четырьмя файлами в нем:
Вот так будет выглядеть полный путь linux к одному из файлов:
Это уже относительный путь linux, который начинается от домашней папки, она обозначается
/. Дальше вы уже можете указывать подпапки, в нашем случае tmp:
Ну или путь файла в linux, относительно текущей папки:
В каждой папке есть две скрытые ссылки, мы сможем их увидеть с помощью ls, выполнив ее с параметром -a:
Первая ссылка указывает на текущую папку (.), вторая (..) указывает на папку уровнем выше. Это открывает еще более широкие возможности для навигации по каталогам. Например, чтобы сослаться на файл в текущей папке можно использовать конструкцию:
Это бесполезно при просмотре содержимого файла. Но очень важно при выполнении программы. Поскольку программа будет сначала искаться в среде PATH, а уже потом в этой папке. А потому, если нужно запустить программу, которая находится в текущей папке и она называется точно также как и та что в каталоге /bin, то без явной ссылки что файл нужно искать в текущей папке ничего не получится.
Вторая ссылка вам позволяет получить доступ к файлам в папке выше текущей. Например:
Такие конструкции могут довольно часто встречаться при компиляции программ. Все эти символы и пути файлов linux вы можете применять не только в терминале, но и в любом файловом менеджере, что может быть очень удобно.
Но терминал Linux предоставляет еще более широкие возможности. Вы можете использовать простые символы замены прямо в адресах файлов или каталогов. Например, можно вывести все файлы, начинающиеся на f:
Или даже можно искать не только в папке tmp, а в любой подпапке домашней папки:
И все это будет работать, возможно, это не всегда нужно и практично. Но в определенных ситуациях может очень сильно помочь. Эти функции реализуются на уровне оболочки Bash, поэтому вы можете применять их в любой команде. Оболочка смотрит сколько файлов было найдено и для каждого из них вызывает команду.
Выводы
Вот и все. Теперь вы знаете все что необходимо, чтобы не только правильно написать путь к файлу linux, но и выполнять более сложные действия, например, поиск файлов или навигация по каталогам с помощью команды cd. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Getting the Absolute (Full) and Relative Path In Linux
This article explains absolute paths and how they differ from relative paths, getting them, and how symbolic links are handled.
FileSystem Paths
A path is the location of a file in a file system. It’s the directions to the file in the folder it is located.
A path consists of a string of characters. Some represent directory names, and a separator character separates the directory names from the file name and extension.
Consider the below path:
- Forward slashes (/) to separate directories from their subdirectories
- Directory Names – the text between the forward slashes
- The file name – in this case, file.txt
Relative Paths
Relative paths are paths that are defined in relation to your current position in the file system.
You can find your current position using the pwd command:
Relative paths begin without a forward slash, or a . or ...
- Paths beginning without a / or with a . start in the current directory
- Paths beginning with .. start in the directory above the current directory (the parent of the current directory)
Example
If you are in the directory /home/user:
…and it contains a file called test.txt, you need only type:
…to view the contents of the file, as you are in the same directory as that file, and can access it using its relative path.
In the above example, the cd command is used to change the directory, and the cat command reads the contents of the file to the screen.
Absolute Paths
Absolute paths can be used from anywhere on the filesystem. They represent the full path of the file from the root (the very top) of the file system hierarchy. They are absolute because it’s the absolute location of the file on the file system. It is not relative to where you are or where you might be; the path will work when called from any location.
Example
Consider again that we are in the directory /home/user:
…and there is a file called another.txt located at /var/temp. Attempting to open it by running:
…will fail because that file doesn’t exist at /home/user. We can, however, access it at its absolute path:
As it provides the full location of the file and does not rely on the relative path we are currently situated.
Paths and Hard / Soft Links (symlinks)
Soft links (symlinks) are just files that point to another file. The absolute path is still the path to the symlink. If you want the path to the linked file itself, you will need to use the readlink command to find the absolute path of the linked file:
Hard links are also absolute paths – the data exists at multiple absolute paths but in only one location on the physical disk.
Brad Morton
I’m Brad, and I’m nearing 20 years of experience with Linux. I’ve worked in just about every IT role there is before taking the leap into software development. Currently, I’m building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I’m up to.
Источник
How can I generate a list of files with their absolute path in Linux?
I am writing a shell script that takes file paths as input.
For this reason, I need to generate recursive file listings with full paths. For example, the file bar has the path:
but, as far as I can see, both ls and find only give relative path listings:
It seems like an obvious requirement, but I can’t see anything in the find or ls man pages.
How can I generate a list of files in the shell including their absolute paths?
26 Answers 26
If you give find an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:
or if your shell expands $PWD to the current directory:
find simply prepends the path it was given to a relative path to the file from that path.
Greg Hewgill also suggested using pwd -P if you want to resolve symlinks in your current directory.
gives the full absolute path. but if the file is a symlink, u’ll get the final resolved name.
Use this for dirs (the / after ** is needed in bash to limit it to directories):
this for files and directories directly under the current directory, whose names contain a . :
this for everything:
In bash, ** is recursive if you enable shopt -s globstar .
This looks only in the current directory. It quotes «$PWD» in case it contains spaces.
Command: ls -1 -d «$PWD/»*
This will give the absolute paths of the file like below.
The $PWD is a good option by Matthew above. If you want find to only print files then you can also add the -type f option to search only normal files. Other options are «d» for directories only etc. So in your case it would be (if i want to search only for files with .c ext):
or if you want all files:
Note: You can’t make an alias for the above command, because $PWD gets auto-completed to your home directory when the alias is being set by bash.
If you give the find command an absolute path, it will spit the results out with an absolute path. So, from the Ken directory if you were to type:
(instead of the relative path find . -name bar -print )
Therefore, if you want an ls -l and have it return the absolute path, you can just tell the find command to execute an ls -l on whatever it finds.
NOTE: There is a space between <> and ;
You’ll get something like this:
If you aren’t sure where the file is, you can always change the search location. As long as the search path starts with «/», you will get an absolute path in return. If you are searching a location (like /) where you are going to get a lot of permission denied errors, then I would recommend redirecting standard error so you can actually see the find results:
( 2> is the syntax for the Borne and Bash shells, but will not work with the C shell. It may work in other shells too, but I only know for sure that it works in Bourne and Bash).
Источник