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

  1. Create files and directories — Use touch and mkdir to create files and directory structures
  2. Copy files and directories — Use cp to duplicate files, preserve attributes, and copy directory trees
  3. Move and rename files and directories — Use mv to relocate and rename files and directories
  4. Delete files and directories safely — Use rm and rmdir with 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
/etcSystem configuration files — edited frequently by admins
/homeUser home directories
/rootHome directory for the root account
/tmpTemporary files — cleared on reboot, world-writable
/varVariable data — logs, mail, databases, spool files
/usrInstalled software, libraries, and documentation
/bin, /sbinEssential user and system binaries
/devDevice files — disks, terminals, null, random
/proc, /sysVirtual 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
Always use mkdir -p in scripts

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
Confirm before and after every operation

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
cp overwrites silently

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
-rRecursive — copy directories and their contents
-pPreserve — keep original permissions, ownership, and timestamps
-aArchive — equivalent to -rp plus preserve symlinks and special files
-vVerbose — 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
mv is instant on the same filesystem

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'
rm is permanent — there is no undo

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.

Test with ls before rm

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 is extremely dangerous

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 characterfile?.txt matches file1.txt, fileA.txt
[abc]Any one of the listed charactersfile[123].txt matches file1.txt, file2.txt, file3.txt
[a-z]Any character in the rangefile[a-z].txt matches filea.txt through filez.txt
[^abc]Any character NOT in the listfile[^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}
The backup shortcut

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-pCreate parents as needed; no error if exists
mkdir-vPrint each directory as it is created
cp-rRecursive — required to copy directories
cp-pPreserve permissions, ownership, timestamps
cp-aArchive — recursive plus preserve all attributes
cp-iPrompt before overwriting
cp-nNever overwrite an existing file
cp-vVerbose — print each file as it is copied
mv-iPrompt before overwriting
mv-nNever overwrite an existing file
mv-vVerbose — print each file as it is moved
rm-rRecursive — required to remove directories
rm-iPrompt before deleting each file
rm-fForce — no prompt, ignore missing files
rm-vVerbose — 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
RHCSA Focus

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.

  1. Write the command to create the directory structure /srv/web/html and /srv/web/logs in one command.
  2. Write the command to back up /etc/httpd/conf/httpd.conf to the same directory with a .bak extension using brace expansion.
  3. Write the command to copy the entire /etc/httpd directory tree to /tmp/httpd-backup, preserving all permissions and timestamps.
  4. What is the difference between rmdir and rm -r?
  5. You want to delete all files ending in .tmp in /var/cache. What two commands do you run, and why do you run them in that order?
  6. You run cp /etc/hosts /tmp/newdir/ but /tmp/newdir/ does not exist. What happens, and how do you fix it?

Knowledge Check — Answers

  1. mkdir -p /srv/web/{html,logs}
    This creates both directories in one command and creates /srv/web as a parent if it does not already exist.
  2. cp /etc/httpd/conf/httpd.conf{,.bak}
    Brace expansion produces two arguments: /etc/httpd/conf/httpd.conf and /etc/httpd/conf/httpd.conf.bak.
  3. cp -a /etc/httpd /tmp/httpd-backup
    The -a flag (archive) copies recursively and preserves all file attributes — permissions, ownership, timestamps, and symbolic links. cp -rp is also correct.
  4. rmdir removes only empty directories and fails if any files remain. rm -r removes a directory and all of its contents recursively, regardless of whether it is empty.
  5. First: ls /var/cache/*.tmp to confirm which files match. Then: rm /var/cache/*.tmp to delete them. Running ls first prevents accidentally deleting more files than intended if the wildcard matches unexpectedly.
  6. cp creates a regular file named /tmp/newdir (not a directory) containing the contents of /etc/hosts. Fix it by first running mkdir -p /tmp/newdir, removing the incorrectly created file with rm /tmp/newdir, and then re-running the cp command.

Key Takeaways

  1. Use mkdir -p to 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.
  2. Back up before you edit or overwrite. cp file{,.bak} is the fastest backup pattern. cp -a preserves all attributes when copying directory trees. cp and mv overwrite silently — use -i when there is any doubt.
  3. rm is permanent — there is no undo. Run ls with the same pattern before rm to confirm which files will be deleted. Use rm -i for interactive confirmation. Be especially careful with rm -rf — double-check the path every time.
  4. Create the destination directory before copying into it. If the destination does not exist, cp creates a file rather than a directory. Always mkdir -p /destination first if there is any doubt the directory exists.

Graded Lab

  • Create the directory structure /tmp/lab/{src,docs,bin,tests} using brace expansion and mkdir -p in a single command
  • Create three text files in /tmp/lab/src using touch with brace expansion
  • Back up /etc/ssh/sshd_config to the same directory with a .bak extension using the brace expansion pattern
  • Copy the entire /etc/ssh directory to /tmp/lab/docs with all permissions preserved — use ls -la on both locations to confirm permissions match
  • Move all three files from /tmp/lab/src into /tmp/lab/bin using a wildcard pattern
  • Use find /tmp/lab -type f to list all files in the lab tree, then use rm -ri /tmp/lab to remove it interactively
RHCSA Objective

"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.