What is a Directory in Linux?
A directory in Linux is a special type of file that acts as a container for other files and directories. Think of it like a folder in a graphical operating system. Linux uses a hierarchical file system, starting from the root directory /
, and everything else (including devices, processes, user data) branches off from there.
Each directory contains entries (filenames) that refer to either files or other directories. Directories help organize the system and user data in a logical and manageable way.
Key directories in Linux include:
/home
– user directories/etc
– configuration files/bin
– essential binaries/var
– variable data like logs/tmp
– temporary files/usr
– user-level programs and data
Create a Directory
Command: mkdir
(Make Directory)
Basic Syntax:
mkdir [OPTIONS] DIRECTORY_NAME
Example:
mkdir testdir
Creates a directory named testdir
in the current working directory.
Commonly Used Options:
-
-p
– Creates parent directories as needed.mkdir -p /home/user/documents/reports/2025
This creates the entire path if it doesn’t already exist.
-
-v
– Verbose, shows what is being done.mkdir -v newdir
Output:
When successful, mkdir
does not show output unless used with -v
.
Remove a Directory
Command: rmdir
(Remove Directory)
Basic Syntax:
rmdir [OPTIONS] DIRECTORY_NAME
Example:
rmdir testdir
This removes the empty directory testdir
.
Important: rmdir
only works on empty directories.
Removing Non-Empty Directories:
Command: rm -r
(Recursive remove)
rm -r dirname
Use -i
for confirmation prompt before deletion:
rm -ri dirname
Use -f
to force delete without prompt:
rm -rf dirname
Be Cautious:
rm -rf
is very powerful and dangerous. It will delete files and directories recursively without warning.
Summary Table
Task | Command | Notes |
---|---|---|
Create directory | mkdir dir | Creates a directory in current path |
Create nested dirs | mkdir -p path/to/dir | Creates parent dirs as needed |
Remove empty dir | rmdir dir | Only works if dir is empty |
Remove dir recursively | rm -r dir | Deletes non-empty dir and contents |
Force remove | rm -rf dir | No confirmation, dangerous |