- Linux Command line Basics – Working with Files and Directories
- Viewing Directories
- What is an Inode?
- Determining the Current Directory
- Displaying the Directory Content
- Displaying the Directory Content With Options
- Displaying File Types
- Changing Directories
- Relative and Absolute Path Name
- Home Directory
- Returning to Your Home Directory
- Основы Linux от основателя Gentoo. Часть 1 (2/4): Управление файлами и директориями
- Использование команд Linux
- Знакомство с ls
- Развернутые списки директорий
- Смотрим на директории
- Рекурсивный и инодный списки
- Понятие инода
- mkdir
- touch
- cat и cp
- Об авторах
- Daniel Robbins
- Chris Houser
- Aron Griffis
Linux Command line Basics – Working with Files and Directories
This post explains how to work with files and directories. This includes tasks, such as locating your position in the directory structure, viewing file contents, copying and moving files and directories, creating and removing files and directories, and searching for files and directories.
Viewing Directories
A directory is a list of references to objects, which can include files, subdirectories, and symbolic links. Each reference consists of two components:
- A name: The name of the object is used to identify and access the object.
- A number: The number specifies the inode in which information about the object is stored.
You can use various commands to display the current directory, view content of a directory, and change directories.
What is an Inode?
An inode is a list of information relating to a particular object, such as a file, directory, or symbolic link. The information held by the inode includes the type of object about which the inode holds information, permissions, ownership information, and the locations in which data is stored.
Determining the Current Directory
The pwd command identifies the full or absolute path name of the current working directory.
Displaying the Directory Content
The ls command displays the content of a directory. The syntax for the ls command is:
Below are few examples of using ls command to list the directory contents.
1. To list the files and directories in the current directory (/export/home/student), enter the ls command without arguments.
2. To display the content of a specific directory within the current working directory, enter the ls command followed by the directory name.
3. To display the content of a directory that is not in the current working directory, enter the ls command with the complete path to that directory.
Displaying the Directory Content With Options
The ls -l command displays a long listing of file information.
The following is a brief explanation of the parts of the long list displayed in the figure above:
- The first character is the file type. It can be a file(-) or directory(d) or symbolic link(l) etc
- The second nine places indicate the file permissions: r means readable, w means writable, x means executable, and the – means denied.
- The third section (one number) is the link count.
- The fourth section is the owner (user).
- The fifth section is the group (user).
- The sixth section is the file size.
- The seventh section is the date.
- The eighth section is the file name.
Some files are hidden from view when you use the ls command. Hidden files often contain information that customizes your work environment. The “ls -la” command lists all files in a directory, including hidden files.
The ls -ld command displays detailed information about a directory without showing its content.
For example, to obtain detailed directory information for the dir1 directory, enter the ls -ld command.
For example, to view a recursive list of the content of the dir1 directory, enter the ls -R dir1 command.
Displaying File Types
Knowing the file type may help you decide the command or program to use for reading the file. The ls -F command or the file command displays the file types. For example:
The following table shows the symbols or indicators used with the “ls –F” command output.
Indicator | File Type |
---|---|
* | Executable |
/ | Directory |
#ERROR! | Socket |
@ | Symbolic link |
| | First In First Out (FIFO) |
The file command also helps determine certain file types. The syntax for the file command is:
For example, to view the file type of the file “test”, enter the file command and specify the name of the file.
The output from the file command is one of the following:
- Text: Text files include American Standard Code for Information Interchange (ASCII) text, English text, command text, and executable shell scripts.
- Data: Data files are created by programs. The file command indicates the type of data file, such as a FrameMaker document, if the type is known. The file command indicates that the file is a data file if the type is unknown.
- Executable or binary: Executable files include 32-bit executable and extensible linking format (ELF) code files and other dynamically linked executable files. Executable files are commands or programs.
Changing Directories
When working within the directory hierarchy, you always have a current working directory. When you initially log in to the system, the current directory is set to your home directory. You can change your current working directory at any time by using the cd command. For example, to change directories from the student directory to the dir1 directory, use the cd command:
When you use the cd command without options or arguments, the current working directory changes to your home directory. In the command line, you can use path name abbreviations to easily navigate to or refer to directories. The table describes the path name abbreviations.
Symbol | Path name |
---|---|
. | Current or working directory |
.. | Parent directory, the directory directly above the current working directory |
For example, to move to the parent directory for dir1, enter the cd .. command.
Confirm the current working directory by using the pwd command.
Relative and Absolute Path Name
You can use either a relative or an absolute path name to move around the directory hierarchy. A relative path name lists the directories in the path relative to the current working directory. An absolute path name lists all the directories in the path, starting with the root (/) directory.
For example, to change directories using a relative path name, enter the cd command with the path name that starts from the current working directory, student.
For instance, to change directories using an absolute path name, enter the cd command with the complete path name from the root (/) directory.
Home Directory
The home directory of a regular user is where the user is placed after logging in. The user can create and store files in the home directory. Often the name of a user’s home directory is the same as the user’s login name. For example, if your user login name is john, your home directory would be /home/john.
Returning to Your Home Directory
You can return to your home directory by using one of the two methods:
1. Use the cd command without arguments.
2. Use the cd command with the absolute path name to your home directory.
You can also navigate to a user’s home directory, using the cd command with a tilde (
) character in front of the username. The tilde (
) character is an abbreviation that equates to the absolute path name of the user.
Note: The tilde (
) character is a shell facility and is not available in all shells.
You can also use the tilde (
) character to represent your home directory in a relative path. The tilde (
) in the following example represents the student home directory.
You can also use the tilde (
) character to navigate to another user’s home directory.
Источник
Основы Linux от основателя Gentoo. Часть 1 (2/4): Управление файлами и директориями
Продолжение перевода первой части руководства. Начало тут.
В данном отрывке рассмотрены команды работы с файловой системой и файлами, такие как ls, mkdir, touch, mv, cp, затронуто использование echo и cat. Рассказано про иноды файловой системы.
Использование команд Linux
Знакомство с ls
А сейчас, мы быстренько пройдемся по команде ls. Скорее всего вы уже хорошо знакомы с этой командой, и знаете, что набрав ls получите список содержимого текущей рабочей директории:
Указав опцию -a, вы можете увидеть полный список, включая скрытые файлы и директории, начинающиеся с «.». Как видно в следующем примере, ls -a выводит также особые связывающие директории «.» и «..»:
Развернутые списки директорий
Вы также можете задать одну и более директорий или файлов в командной строке с ls. Если вы укажите файл, то ls покажет вам только этот файл. А если зададите директорию, то ls выдаст ее содержимое. Опция -l очень удобна, когда необходимо посмотреть права доступа, владельца, время последнего изменения и размер в списке содержимого директории.
В следующем примере мы использовали опцию -l чтобы отобразить содержимое моей директории /usr:
Первая колонка показывает информацию о правах доступа для каждого элемента. Чуть позже я объясню, как её интерпретировать. Следующая колонка содержит числа ссылок на каждый элемент файловой системы, позже мы вернемся к этому. Третья и четвертая колонки — это список владельцев и групп, соответственно. Пятая колонка — размер объекта. Шестая — время последнего изменения (mtime) объекта. И наконец, последняя колонка с именами объектов. Если файлы являются символическими ссылками, то вы увидите стрелку -> и путь, куда указывает эта символическая ссылка.
Смотрим на директории
Иногда вы захотите взглянуть на директорию, а не внутрь нее. В этом случае вы можете указать опцию -d, которая скажет ls рассматривать любую директорию, как внутреннюю:
Рекурсивный и инодный списки
Так вы можете использовать -d чтобы смотреть на директорию, но также можно использовать -R для противоположного: не только лишь глянуть внутрь директории, но и рекурсивно посмотреть все директории с файлами внутри нее! Мы не включим в руководство никакого примера вывода для этой опции (поскольку обычно он очень объемный), но возможно вы захотите попробовать несколько команд ls -R и ls -Rl, чтобы почувствовать как это работает.
Наконец, опция -i может использоваться для отображения числа инодов для объектов в списке файловой системы:
Понятие инода
Каждому объекту файловой системы назначен уникальный индекс, называемый номером инода. Это может показаться банальным, но понятие инодов очень важно для понимания большинства операций в файловой системе. Рассмотрим например ссылки «.» и «..», которые появляются в каждой директории. Чтобы полностью понять, чем на самом деле является директория «..», мы сперва взглянем на номер инода у /usr/local:
$ ls -id /usr/local
5120 /usr/local
У директории /usr/local номер инода равен 5120. А теперь посмотрим номер инода у /usr/local/bin/..:
$ ls -id /usr/local/bin/..
5120 /usr/local/bin/..
Как видно, директория /usr/local/bin/.. имеет такой же номер, как у /usr/local! Посмотрим, как можно справиться с этим шокирующим откровением. В прошлом мы полагали, что /usr/local сама является директорией. Теперь же, мы обнаружили, что фактически директория — это инод с номером 5120, и нашли, по меньшей мере, два элемента (называемых «ссылками»), которые указывают на данный инод. И /usr/local, и /usr/local/bin/.. — ссылки на 5120-ый инод. Хотя этот инод и существует только в одном месте на диске, тем не менее на него может быть множество ссылок.
На самом деле, мы даже можем увидеть общее количество ссылок ведущих на этот, 5120 инод, используя команду ls -dl:
Если взглянуть на вторую колонку слева, то видно, что на директорию /usr/local (инод 5120) ссылаются восемь раз. На моей системе на этот инод ведут следующие пути:
/usr/local
/usr/local/.
/usr/local/bin/..
/usr/local/games/..
/usr/local/lib/..
/usr/local/sbin/..
/usr/local/share/..
/usr/local/src/..
mkdir
Давайте быстренько пройдемся по команде mkdir, которая используется для создания новых директорий. Следующий пример создает три новых директории, tic, tac, и toe, все внутри /tmp:
$ cd /tmp
$ mkdir tic tac toe
По умолчанию, команда mkdir не создает для вас родительские директории; весь путь вплоть до последнего (создаваемого) элемента должен существовать. Так, если вы захотите создать вложенные директории won/der/ful, вам придется выполнить три отдельные команды mkdir:
$ mkdir won/der/ful
mkdir: cannot create directory `won/der/ful’: No such file or directory
$ mkdir won
$ mkdir won/der
$ mkdir won/der/ful
Однако, у mkdir есть очень удобная опция -p, которая говорит mkdir создавать любые отсутствующие родительские директории, как можете увидеть тут:
$ mkdir -p easy/as/pie
В целом очень просто. Чтобы узнать больше о команде mkdir наберите man mkdir и прочитайте инструкцию. Это же касается почти всех команд, рассмотренных здесь (например man ls), исключая cd, которая встроена в bash.
touch
Сейчас мы собираемся окинуть взглядом команды cp и mv, используемые для копирования, переименования и перемещения файлов и директорий. Но начнем обзор воспользовавшись командой touch, чтобы создать файл в /tmp:
Команда touch обновляет «mtime» (время последней модификации — прим. пер.) файла, если тот существует (вспомните шестую колонку в выводе ls -l). Если файл не существует, то новый, пустой файл будет создан. Сейчас у вас должен быть файл /tmp/copyme с нулевым размером.
Теперь, когда файл существует, давайте добавим немного данных в него. Можно сделать это с помощью команды echo, которая принимает аргументы и печатает их на стандартный вывод. Сперва, команда echo сама по себе:
$ echo «firstfile»
firstfile
А сейчас, та же команда echo, но с перенаправлением вывода:
$ echo «firstfile» > copyme
Знак «больше» сообщает оболочке записывать вывод echo в файл по имени copyme. Этот файл будет создан, если не существовал, или перезаписан, если существует. Набрав ls -l, увидим, что файл copyme имеет размер в 10 байт, так как содержит слово firstfile и символ новой строки:
cat и cp
Чтобы вывести содержимое файла на терминал, используйте команду cat:
$ cat copyme
firstfile
Сейчас, мы можем воспользоваться основным вызовом команды cp для создания файла copiedme из оригинального copyme:
$ cp copyme copiedme
Ниже проверим, что это действительно разные файлы; у них отличаются номера инодов:
А сейчас давайте воспользуемся командой mv для переименования copiedme в movedme. Номер иноды останется прежний; однако, имя файла, указывающее на инод, изменится.
Номер инода у перемещаемого файла остается прежним до тех пор, пока файл назначения находится в той же файловой системе, что и исходный файл. Мы подробнее рассмотрим файловую систему в третьей части нашего руководства.
Пока мы рассказываем об mv, давайте посмотрим, как еще можно использовать эту команду. mv, помимо возможности переименовать файлы, позволяет перемещать один или более файлов в другое место в иерархии директорий. Например, чтобы переместить /var/tmp/myfile.txt в директорию /home/drobbins (которая является моей домашней), я наберу (а мог бы воспользоваться
$ mv /var/tmp/myfile.txt /home/drobbins
После этого myfile.txt будет перемещен в /home/drobbins/myfile.txt. И если /home/drobbins располагается в другой файловой системе, нежели /var/tmp, команда mv скопирует myfile.txt в новую файловую систему и удалит его из старой. Как вы уже могли догадаться, когда myfile.txt перемещается между файловыми системами, то myfile.txt на новом месте получает новый номер инода. Это все потому, что у каждой файловой системы свой независимый набор номеров инодов.
Мы также можем воспользоваться mv для перемещения нескольких файлов в одну директорию. К примеру, чтобы переместить myfile1.txt и myarticle3.txt в /home/drobbins, потребуется набрать:
$ mv /var/tmp/myfile1.txt /var/tmp/myarticle3.txt /home/drobbins
Об авторах
Daniel Robbins
Дэниэль Роббинс — основатель сообщества Gentoo и создатель операционной системы Gentoo Linux. Дэниэль проживает в Нью-Мехико со свой женой Мэри и двумя энергичными дочерьми. Он также основатель и глава Funtoo, написал множество технических статей для IBM developerWorks, Intel Developer Services и C/C++ Users Journal.
Chris Houser
Крис Хаусер был сторонником UNIX c 1994 года, когда присоединился к команде администраторов университета Тэйлора (Индиана, США), где получил степень бакалавра в компьютерных науках и математике. После он работал во множестве областей, включая веб-приложения, редактирование видео, драйвера для UNIX и криптографическую защиту. В настоящий момент работает в Sentry Data Systems. Крис также сделал вклад во множество свободных проектов, таких как Gentoo Linux и Clojure, стал соавтором книги The Joy of Clojure.
Aron Griffis
Эйрон Гриффис живет на территории Бостона, где провел последнее десятилетие работая в Hewlett-Packard над такими проектами, как сетевые UNIX-драйвера для Tru64, сертификация безопасности Linux, Xen и KVM виртуализация, и самое последнее — платформа HP ePrint. В свободное от программирования время Эйрон предпочитает размыщлять над проблемами программирования катаясь на своем велосипеде, жонглируя битами, или болея за бостонскую профессиональную бейсбольную команду «Красные Носки».
Источник