Create and Remove Directory Structures with mkdir, rmdir, and rm
In this step, you will learn how to create and remove directories. Organizing files into a hierarchical structure of directories is a fundamental task in Linux. We will use the mkdir command to create directories, rmdir to remove empty directories, and rm to remove directories and all of their contents. All commands will be executed from your default directory, ~/project.
First, let's create a simple directory. The mkdir command stands for "make directory".
In your terminal, execute the following command to create a directory named cars:
mkdir cars
To verify that the directory has been created, you can use the ls -ld command. The -l option provides a long listing format, and the -d option lists the directory entry itself, not its contents.
ls -ld cars
You should see output similar to this, confirming the creation of the cars directory. The d at the beginning of the permissions string indicates that it is a directory.
drwxr-xr-x 2 labex labex 4096 May 20 10:30 cars
Now, let's remove this directory. The rmdir command is used to remove empty directories.
rmdir cars
Verify its removal by running the ls -ld command again.
ls -ld cars
This time, you will receive an error message because the directory no longer exists. This confirms that rmdir was successful.
ls: cannot access 'cars': No such file or directory
The rmdir command only works on empty directories. What if we have a structure of nested directories? Let's try to create a directory structure pastry/pies/cakes. To create parent directories as needed, we must use the -p (parents) option with mkdir.
Execute the following command:
mkdir -p pastry/pies/cakes
To view the entire directory structure you just created, use the ls command with the -l (long format) and -R (recursive) options.
ls -lR pastry
The output will show the pastry directory and its subdirectories, pies and cakes.
pastry:
total 4
drwxr-xr-x 3 labex labex 4096 May 20 10:35 pies
pastry/pies:
total 4
drwxr-xr-x 2 labex labex 4096 May 20 10:35 cakes
pastry/pies/cakes:
total 0
Now, let's try to remove the pastry directory using rmdir.
rmdir pastry
Why did this command fail? The terminal will show an error message:
rmdir: failed to remove 'pastry': Directory not empty
This is because rmdir can only delete empty directories, and pastry contains the pies subdirectory.
To remove a directory and all of its contents (including subdirectories and files), you must use the rm command with the -r (recursive) option. Be very careful with this command, as it can permanently delete data.
rm -r pastry
This command will not produce any output if successful. You can verify that the pastry directory has been completely removed by running ls -ld pastry again, which should result in a "No such file or directory" error.
ls -ld pastry