RED HAT ENTERPRISE LINUX
Managing Files
and Directories
Create, delete, copy, and move files and directories
CIS126RH | RHEL System Administration 1
Mesa Community College
File and directory management is the most frequently performed task on any Linux system. Creating organized directory structures, safely copying configuration files before editing them, moving files into place after processing, and removing what is no longer needed are all daily operations for a RHEL administrator. These skills are tested directly on the RHCSA exam.
Learning Objectives
-
Create files and directories —
Use
touchandmkdirto create files and directory structures -
Copy files and directories —
Use
cpto duplicate files, preserve attributes, and copy directory trees -
Move and rename files and directories —
Use
mvto relocate and rename files and directories -
Delete files and directories safely —
Use
rmandrmdirwith appropriate options and safety habits
Linux Filesystem Layout
Understanding where files belong in the filesystem makes every file operation faster and safer.
| Directory | Contents |
|---|---|
/ | Root of the filesystem — everything is under here |
/etc | System configuration files — edited frequently by admins |
/home | User home directories |
/root | Home directory for the root account |
/tmp | Temporary files — cleared on reboot, world-writable |
/var | Variable data — logs, mail, databases, spool files |
/usr | Installed software, libraries, and documentation |
/bin, /sbin | Essential user and system binaries |
/dev | Device files — disks, terminals, null, random |
/proc, /sys | Virtual filesystems — kernel and process information |
Absolute and Relative Paths
Every file operation requires specifying a path. Understanding the two types of paths prevents the most common file management mistakes.
| Type | Starts with | Relative to | Example |
|---|---|---|---|
| Absolute | / |
The root of the filesystem — always the same regardless of where you are | /etc/ssh/sshd_config |
| Relative | Anything else | Your current working directory — changes as you cd |
ssh/sshd_config |
Special Path Shortcuts
| Shortcut | Refers to |
|---|---|
~ | Your home directory (/home/student or /root) |
. | The current directory |
.. | The parent directory — one level up |
- | The previous directory you were in (used with cd -) |
Creating Files and Directories
touch — Create Files
# Create one or more empty files
$ touch report.txt
$ touch file1.txt file2.txt file3.txt
# touch on an existing file updates its timestamp without changing content
$ touch existing-file.txt
mkdir — Create Directories
# Create a single directory
$ mkdir /tmp/project
# Create multiple directories at once
$ mkdir /tmp/project/src /tmp/project/docs /tmp/project/bin
# Create a full path in one command — -p creates parents as needed
$ mkdir -p /tmp/project/src/utils
# -p does not error if the directory already exists
$ mkdir -p /tmp/project
The -p flag creates all missing parent directories and silently succeeds
if the directory already exists. This makes scripts safe to run more than once.
Listing Files and Directories
ls lists directory contents. Its options control what is shown and how.
# Basic listing of current directory
$ ls
# Long format — shows permissions, owner, size, and date
$ ls -l /etc/ssh
-rw-r--r-- 1 root root 3905 May 25 09:00 sshd_config
# Show hidden files (names starting with a dot)
$ ls -la ~
# Human-readable sizes
$ ls -lh /var/log
# Sort by modification time — newest first
$ ls -lt /var/log
# Recursive — list all files in all subdirectories
$ ls -lR /tmp/project
Run ls -l before copying or deleting to confirm the source exists,
and after the operation to confirm the result is what you expected.
Copying Files with cp
cp copies a source file to a destination. The original is unchanged.
# Copy a file to another location
$ cp /etc/ssh/sshd_config /tmp/sshd_config.bak
# Copy into a directory — keeps the original filename
$ cp /etc/ssh/sshd_config /tmp/
# Copy and rename at the same time
$ cp report.txt report-final.txt
# Copy multiple files into a directory
$ cp /etc/ssh/sshd_config /etc/ssh/ssh_config /tmp/
# Prompt before overwriting an existing file
$ cp -i source.txt dest.txt
If the destination file already exists, cp overwrites it without asking.
Use -i (interactive) to be prompted before overwriting, or
-n to never overwrite an existing file.
Copying Directories with cp -r
By default, cp refuses to copy a directory. The -r flag
enables recursive copying of an entire directory tree.
# Copy a directory tree to a new location
$ cp -r /etc/ssh /tmp/ssh-backup
# Copy into an existing directory — creates ssh/ inside it
$ cp -r /etc/ssh /tmp/backups/
# Copy and preserve permissions, ownership, and timestamps
$ cp -rp /etc/ssh /tmp/ssh-backup
# Copy and preserve all attributes — equivalent to -rp --preserve=all
$ cp -a /etc/ssh /tmp/ssh-backup
| Flag | Effect |
|---|---|
-r | Recursive — copy directories and their contents |
-p | Preserve — keep original permissions, ownership, and timestamps |
-a | Archive — equivalent to -rp plus preserve symlinks and special files |
-v | Verbose — print each filename as it is copied |
Moving and Renaming with mv
mv moves or renames files and directories. Unlike cp, the
original is removed — there is only one copy after the operation.
# Rename a file
$ mv report-draft.txt report-final.txt
# Move a file to a different directory — keeps the same name
$ mv report-final.txt /tmp/reports/
# Move and rename at the same time
$ mv /tmp/draft.conf /etc/myapp/production.conf
# Move multiple files into a directory
$ mv file1.txt file2.txt file3.txt /tmp/archive/
# Rename a directory
$ mv /tmp/old-project /tmp/new-project
# Prompt before overwriting an existing file
$ mv -i source.txt dest.txt
Moving a file within the same filesystem only updates the directory entry — no data
is copied. Moving across filesystems (for example, from /tmp to
/home) copies the data then deletes the original.
Deleting Files with rm
rm removes files. There is no trash or recycle bin — deleted files are gone.
# Delete a single file
$ rm old-report.txt
# Delete multiple files
$ rm file1.txt file2.txt file3.txt
# Prompt before deleting each file — the safe habit
$ rm -i important-file.txt
# Show what is being deleted
$ rm -v old-report.txt
removed 'old-report.txt'
Linux does not have a recycle bin at the command line. Once rm removes a
file, the data is gone. Always confirm you are deleting the correct files, and
consider using -i to prompt before each deletion.
Run ls file-pattern* first to see exactly which files match your pattern
before running rm file-pattern*. This prevents accidentally deleting
more files than intended.
Deleting Directories
rmdir — Remove Empty Directories Only
# Remove an empty directory
$ rmdir /tmp/empty-dir
# Remove a chain of empty parent directories
$ rmdir -p /tmp/a/b/c
# rmdir fails if the directory contains any files
$ rmdir /tmp/non-empty
rmdir: failed to remove '/tmp/non-empty': Directory not empty
rm -r — Remove a Directory and All Its Contents
# Delete a directory tree — prompts for each file
$ rm -ri /tmp/project
# Delete without prompting — use with extreme caution
$ rm -rf /tmp/project
rm -rf /tmp/project deletes everything in that directory tree instantly
and permanently. A typo in the path — such as a misplaced space — can delete the
wrong directory entirely. Always double-check the path before pressing Enter.
Wildcards and Globbing
The shell expands wildcard patterns into matching filenames before running any command. This works with all file management commands.
| Wildcard | Matches | Example |
|---|---|---|
* | Any string of characters, including none | *.txt matches all .txt files |
? | Any single character | file?.txt matches file1.txt, fileA.txt |
[abc] | Any one of the listed characters | file[123].txt matches file1.txt, file2.txt, file3.txt |
[a-z] | Any character in the range | file[a-z].txt matches filea.txt through filez.txt |
[^abc] | Any character NOT in the list | file[^0-9].txt matches non-numeric suffixes |
# Copy all .conf files to a backup directory
$ cp /etc/ssh/*.conf /tmp/conf-backup/
# Delete all .bak files in the current directory
$ ls *.bak # confirm first
$ rm *.bak # then delete
Brace Expansion
Brace expansion generates multiple strings from a single pattern — useful for creating or operating on groups of related files or directories in one command.
# Create multiple directories at once
$ mkdir -p /srv/project/{src,docs,tests,bin}
# Equivalent to: mkdir -p /srv/project/src /srv/project/docs ...
# Create a backup with a .bak extension alongside the original
$ cp /etc/ssh/sshd_config{,.bak}
# Equivalent to: cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Create numbered files
$ touch report-{01..05}.txt
report-01.txt report-02.txt report-03.txt report-04.txt report-05.txt
# Remove old log rotations in one command
$ rm /var/log/messages-{1..4}
cp /etc/ssh/sshd_config{,.bak} is the fastest way to back up a file
before editing it. The empty string before the comma expands to the original name;
.bak is appended for the copy.
Command Options Quick Reference
| Command | Key options | Effect |
|---|---|---|
mkdir | -p | Create parents as needed; no error if exists |
mkdir | -v | Print each directory as it is created |
cp | -r | Recursive — required to copy directories |
cp | -p | Preserve permissions, ownership, timestamps |
cp | -a | Archive — recursive plus preserve all attributes |
cp | -i | Prompt before overwriting |
cp | -n | Never overwrite an existing file |
cp | -v | Verbose — print each file as it is copied |
mv | -i | Prompt before overwriting |
mv | -n | Never overwrite an existing file |
mv | -v | Verbose — print each file as it is moved |
rm | -r | Recursive — required to remove directories |
rm | -i | Prompt before deleting each file |
rm | -f | Force — no prompt, ignore missing files |
rm | -v | Verbose — print each file as it is removed |
Finding Files with find
find searches the filesystem for files matching criteria — by name, type,
size, owner, or modification time. Results can be piped into file management commands.
# Find files by name
$ find /etc -name 'sshd_config'
# Find all .conf files under /etc
$ find /etc -name '*.conf'
# Find files by type — f=file, d=directory, l=symlink
$ find /tmp -type f
# Find files modified in the last 24 hours
$ find /var/log -mtime -1
# Find and delete — confirm with -print first
$ find /tmp -name '*.bak' -print
$ find /tmp -name '*.bak' -delete
find by name and type are the most common exam uses. Always use
-print first to confirm the results before using -delete
or piping to rm.
Common Mistakes
| Mistake | What goes wrong | Prevention |
|---|---|---|
Forgetting -r with cp or rm on a directory |
Command refuses to act — error: is a directory | Add -r whenever the source is a directory |
Overwriting a file with cp or mv |
Destination file content is silently replaced | Use -i to prompt, or -n to never overwrite |
Deleting files with rm that cannot be recovered |
Data is permanently gone — no undo | Use -i for interactive confirmation; run ls first |
Typo in path with rm -rf |
Deletes the wrong directory tree permanently | Run ls -l path first; consider rm -ri instead |
mkdir failing because parents do not exist |
Error: no such file or directory | Use mkdir -p to create the full path |
| Copying into a directory that does not exist | cp creates a file with the directory's name instead of placing
the file inside it |
Create the destination directory with mkdir -p first |
Knowledge Check
Answer these before moving to the next slide.
- Write the command to create the directory structure
/srv/web/htmland/srv/web/logsin one command. - Write the command to back up
/etc/httpd/conf/httpd.confto the same directory with a.bakextension using brace expansion. - Write the command to copy the entire
/etc/httpddirectory tree to/tmp/httpd-backup, preserving all permissions and timestamps. - What is the difference between
rmdirandrm -r? - You want to delete all files ending in
.tmpin/var/cache. What two commands do you run, and why do you run them in that order? - You run
cp /etc/hosts /tmp/newdir/but/tmp/newdir/does not exist. What happens, and how do you fix it?
Knowledge Check — Answers
mkdir -p /srv/web/{html,logs}
This creates both directories in one command and creates/srv/webas a parent if it does not already exist.cp /etc/httpd/conf/httpd.conf{,.bak}
Brace expansion produces two arguments:/etc/httpd/conf/httpd.confand/etc/httpd/conf/httpd.conf.bak.cp -a /etc/httpd /tmp/httpd-backup
The-aflag (archive) copies recursively and preserves all file attributes — permissions, ownership, timestamps, and symbolic links.cp -rpis also correct.rmdirremoves only empty directories and fails if any files remain.rm -rremoves a directory and all of its contents recursively, regardless of whether it is empty.- First:
ls /var/cache/*.tmpto confirm which files match. Then:rm /var/cache/*.tmpto delete them. Running ls first prevents accidentally deleting more files than intended if the wildcard matches unexpectedly. cpcreates a regular file named/tmp/newdir(not a directory) containing the contents of/etc/hosts. Fix it by first runningmkdir -p /tmp/newdir, removing the incorrectly created file withrm /tmp/newdir, and then re-running the cp command.
Key Takeaways
-
Use
mkdir -pto create directory structures. It creates all missing parent directories in one command and does not error if the directory already exists — making it safe for scripts and repeated use. -
Back up before you edit or overwrite.
cp file{,.bak}is the fastest backup pattern.cp -apreserves all attributes when copying directory trees.cpandmvoverwrite silently — use-iwhen there is any doubt. -
rmis permanent — there is no undo. Runlswith the same pattern beforermto confirm which files will be deleted. Userm -ifor interactive confirmation. Be especially careful withrm -rf— double-check the path every time. -
Create the destination directory before copying into it.
If the destination does not exist,
cpcreates a file rather than a directory. Alwaysmkdir -p /destinationfirst if there is any doubt the directory exists.
Graded Lab
- Create the directory structure
/tmp/lab/{src,docs,bin,tests}using brace expansion andmkdir -pin a single command - Create three text files in
/tmp/lab/srcusingtouchwith brace expansion - Back up
/etc/ssh/sshd_configto the same directory with a.bakextension using the brace expansion pattern - Copy the entire
/etc/sshdirectory to/tmp/lab/docswith all permissions preserved — usels -laon both locations to confirm permissions match - Move all three files from
/tmp/lab/srcinto/tmp/lab/binusing a wildcard pattern - Use
find /tmp/lab -type fto list all files in the lab tree, then userm -ri /tmp/labto remove it interactively
"Create, delete, copy, and move files and directories." These operations appear in virtually every other exam task — fluency here saves time across the entire exam.