- Navigating Your File System in Linux
- This chapter is from the book
- This chapter is from the book
- This chapter is from the book
- List Files and Folders
- 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
- Переменная PATH в Linux
- Переменная PATH в Linux
- Выводы
Navigating Your File System in Linux
This chapter is from the book
This chapter is from the book
This chapter is from the book
This chapter introduces the basic commands you’ll find yourself using several times every day. Think of these as the hammer, screwdriver, and pliers that a carpenter keeps in the top of his toolbox. After you learn these commands, you can start controlling your shell and finding out all sorts of interesting things about your files, folders, data, and environment. In particular, you’ll be learning about some of the metadata—the data describing your data—that Linux has to keep track of, and it may just surprise you how much there is.
When I updated this book for its second edition, I removed the section about mkdir -v (which shows you what mkdir is doing as it does it) and rm -v (which does the same thing, but for rm). You can find the original text on my website, www.granneman.com/linux-redactions.
Also, I took the sections on touch, mkdir, cp, mv, rm, and rmdir and used them to create a new Chapter 3 titled “Creation and Destruction” (which of course renumbered everything after it!). Finally, the section on su was moved to Chapter 8, “Ownership and Permissions,” which makes a lot more sense.
List Files and Folders
The ls command is probably the one that people find themselves using the most. After all, before you can manipulate and use files in a directory (remember, file and directory are interchangeable), you first have to know what files are available. That’s where ls comes in, as it lists the files and subdirectories found in a directory.
The ls command might sound simple—just show me the files!—but there are a surprising number of permutations to this amazingly pliable command, as you’ll see.
Typing ls lists the contents of the directory in which you’re currently working. When you first log in to your shell, you’ll find yourself in your home directory. Enter ls, and you might see something like the following:
Источник
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.
Источник
Переменная 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 и как добавлять к её значению новые пути поиска исполняемых и связанных с ними файлов. Как видите, всё делается достаточно просто. Таким образом вы можете добавить столько папок для поиска и хранения исполняемых файлов, сколько вам требуется.
Источник