Making Directories
In this lesson, we introduce you to directories and show you how to make one.
Beyond files, a set of directory-related system calls enable you to make, read, and delete directories. Note you can never write to a directory directly. Because the format of the directory is considered file system metadata, the file system considers itself responsible for the integrity of directory data. Thus, you can only update a directory indirectly by, for example, creating files, directories, or other object types within it. In this way, the file system makes sure that directory contents are as expected.
To create a directory, a single system call, mkdir()
, is available. The eponymous mkdir
program can be used to create such a directory. Let’s take a look at what happens when we run the mkdir
program to make a simple directory called foo
:
prompt> strace mkdir foo...mkdir("foo", 0777) = 0...prompt>
Try it out yourself:
When such a directory is created, it is considered “empty”, although it does have a bare minimum of contents. Specifically, an empty directory has two entries: one entry that refers to itself, and one entry that refers to its parent. The former is referred to as the .
(dot) directory, and the latter as ..
(dot-dot). You can see these directories by passing a flag (-a
) to the program ls
:
prompt> ls -a./ ../prompt> ls -altotal 8drwxr-x--- 2 remzi remzi 6 Apr 30 16:17 ../drwxr-x--- 26 remzi remzi 4096 Apr 30 16:17 ../
TIP: BE WARY OF POWERFUL COMMANDS
The program rm provides us with a great example of powerful commands, and how sometimes too much power can be a bad thing. For example, to remove a bunch of files at once, you can type something like:
prompt> rm *
where the
*
will match all files in the current directory. But sometimes you want to also delete the directories too, and in fact all of their contents. You can do this by tellingrm
to recursively descend into each directory, and remove its contents too:prompt> rm -rf *
Where you get into trouble with this small string of characters is when you issue the command, accidentally, from the root directory of a file system, thus removing every file and directory from it. Oops!
Thus, remember the double-edged sword of powerful commands; while they give you the ability to do a lot of work with a small number of keystrokes, they also can quickly and readily do a great deal of harm.
Get hands-on with 1400+ tech skills courses.