RED HAT ENTERPRISE LINUX

File Management

Copy, Move, Create, Delete, and Organize

CIS126RH | RHEL System Administration 1
Mesa Community College

Learning Objectives

1
Create files and directories

Use touch, mkdir, and other methods to create new items

2
Copy files and directories

Duplicate files with cp, preserving attributes when needed

3
Move and rename files

Relocate and rename with the mv command

4
Delete files and directories safely

Remove items with rm and rmdir, understanding the risks

5
Organize with wildcards and patterns

Use globbing to work with multiple files efficiently

Paths: Absolute vs Relative

Paths can be absolute (from root) or relative (from current directory).

# Absolute paths start from root (/)
[user@host ~]$ cat /etc/hostname
[user@host ~]$ ls /var/log/messages

# Relative paths start from current directory
[user@host ~]$ pwd
/home/student
[user@host ~]$ cat Documents/notes.txt    # Relative to /home/student

# Special path symbols
.     Current directory
..    Parent directory
~     Home directory (/home/username)
~bob  Bob's home directory (/home/bob)

Creating Files: touch

touch creates empty files or updates timestamps on existing files.

# Create a single empty file
[user@host ~]$ touch newfile.txt
[user@host ~]$ ls -l newfile.txt
-rw-r--r--. 1 student student 0 Jan 20 10:00 newfile.txt

# Create multiple files at once
[user@host ~]$ touch file1.txt file2.txt file3.txt

# Create file in a specific directory
[user@host ~]$ touch Documents/report.txt

# If file exists, touch updates its timestamp
[user@host ~]$ touch oldfile.txt
[user@host ~]$ ls -l oldfile.txt
-rw-r--r--. 1 student student 100 Jan 20 10:05 oldfile.txt
Note: touch creates files with zero bytes. Use editors or redirection to add content.

Other Ways to Create Files

# Redirect output to create file with content
[user@host ~]$ echo "Hello World" > greeting.txt

# Append to file (creates if it does not exist)
[user@host ~]$ echo "Another line" >> greeting.txt

# Create empty file with redirection
[user@host ~]$ > emptyfile.txt

# Create multi-line file with heredoc
[user@host ~]$ cat > notes.txt << EOF
Line 1
Line 2
Line 3
EOF

# Use text editors (file created on save)
[user@host ~]$ vim newdocument.txt
Caution: > overwrites existing content. >> appends. Be careful with > on important files!

Creating Directories: mkdir

mkdir creates new directories. Use -p to create parent directories as needed.

# Create a single directory
[user@host ~]$ mkdir projects

# Create multiple directories
[user@host ~]$ mkdir dir1 dir2 dir3

# Without -p, nested creation fails
[user@host ~]$ mkdir projects/web/frontend
mkdir: cannot create directory 'projects/web/frontend': No such file or directory

# -p creates all parents automatically
[user@host ~]$ mkdir -p projects/web/frontend
[user@host ~]$ mkdir -p projects/mobile/{ios,android}

Verifying Directory Structures

# Verify with ls -R (recursive)
[user@host ~]$ ls -R projects
projects:
mobile  web

projects/mobile:
android  ios

projects/web:
backend  frontend

# Or with tree for a visual view
[user@host ~]$ tree projects
projects
├── mobile
│   ├── android
│   └── ios
└── web
    ├── backend
    └── frontend
mkdir -p is also safe to run on existing paths — it will not error or overwrite anything already there.

Copying Files: cp Basics

cp duplicates files. The original remains unchanged; a new copy is created.

cp [options] source destination
# Copy file to new name (same directory)
[user@host ~]$ cp report.txt report_backup.txt

# Copy file to different directory (keeps name)
[user@host ~]$ cp report.txt Documents/

# Copy multiple files to a directory
[user@host ~]$ cp file1.txt file2.txt file3.txt Documents/

# Use -i for interactive (prompts before overwrite)
[user@host ~]$ cp -i newdata.txt olddata.txt
cp: overwrite 'olddata.txt'? y
Warning: cp overwrites existing destination files silently by default. Use -i for safety.

Copying Directories

# Without -r, directories are silently skipped
[user@host ~]$ cp projects backup_projects
cp: -r not specified; omitting directory 'projects'

# Use -r to copy directory and all contents
[user@host ~]$ cp -r projects backup_projects

# -v shows each file being copied
[user@host ~]$ cp -rv projects backup_projects
'projects' -> 'backup_projects'
'projects/file1.txt' -> 'backup_projects/file1.txt' ...

# -p preserves permissions, ownership, timestamps
[user@host ~]$ cp -rp projects backup_projects

# -a (archive) preserves everything — best for backups
[root@host ~]# cp -a /etc /backup/etc_backup
-a is archive mode: combines -r with full attribute preservation. Use it for backups and when you need an exact replica.

Moving and Renaming: mv

mv relocates files and directories. It also serves as the rename command — moving to the same directory with a new name.

mv [options] source destination
# Rename a file
[user@host ~]$ mv oldname.txt newname.txt

# Move file to different directory
[user@host ~]$ mv report.txt Documents/

# Move and rename simultaneously
[user@host ~]$ mv draft.txt Documents/final_report.txt

# Move multiple files to directory
[user@host ~]$ mv file1.txt file2.txt file3.txt archive/

# Rename a directory
[user@host ~]$ mv old_project new_project
Key difference: cp keeps the original. mv removes the source — it is gone from its original location.

mv Options and Safety

# mv overwrites without warning by default
[user@host ~]$ mv newfile.txt existingfile.txt  # existingfile.txt is GONE

# -i prompts before overwrite
[user@host ~]$ mv -i newfile.txt existingfile.txt
mv: overwrite 'existingfile.txt'? n

# -n never overwrites (silent if destination exists)
[user@host ~]$ mv -n source.txt destination.txt

# -v shows what is happening
[user@host ~]$ mv -v projects/ archive/
renamed 'projects/' -> 'archive/projects'

# --backup creates numbered backups before overwriting
[user@host ~]$ mv --backup=numbered important.txt Documents/
Critical: mv can destroy data instantly — both source is moved away AND destination is overwritten. Two files become one. Use -i when unsure.

Deleting Files: rm

rm permanently deletes files. There is no trash can — deleted files are gone.

# Remove a single file
[user@host ~]$ rm unwanted.txt

# Remove multiple files
[user@host ~]$ rm file1.txt file2.txt file3.txt

# Interactive mode — confirm each deletion
[user@host ~]$ rm -i important.txt
rm: remove regular file 'important.txt'? y

# Force removal (no prompts, no errors for missing files)
[user@host ~]$ rm -f maybe_exists.txt

# Verbose — show what is being deleted
[user@host ~]$ rm -v old_file.txt
removed 'old_file.txt'
Warning: rm is permanent. There is no undo. Double-check before pressing Enter.

Deleting Directories

# rmdir removes empty directories only (safe)
[user@host ~]$ rmdir empty_folder
[user@host ~]$ rmdir folder_with_files
rmdir: failed to remove 'folder_with_files': Directory not empty

# rm -r removes directories and all contents
[user@host ~]$ rm -r old_project

# rm -ri — interactive recursive deletion (safest)
[user@host ~]$ rm -ri old_project
rm: descend into directory 'old_project'? y
rm: remove regular file 'old_project/file.txt'? y
rm: remove directory 'old_project'? y

# rm -rf — the dangerous combination (no prompts)
[user@host ~]$ rm -rf old_project
DANGER: A typo like rm -rf / or rm -rf ~/* can destroy your system or all your files. Always verify the path!

Wildcards: Globbing

Wildcards match multiple files by pattern. The shell expands them before the command runs.

PatternMatchesExample
*Any characters (zero or more)*.txt matches all .txt files
?Any single characterfile?.txt matches file1.txt
[abc]Any one character from the setfile[123].txt matches file1.txt
[a-z]Any one character in rangefile[a-c].txt matches filea.txt
[!abc]Any character NOT in the setfile[!0-9].txt matches fileA.txt

Using Wildcards Safely

# Copy all .txt files to backup
[user@host ~]$ cp *.txt backup/

# Delete .tmp files — ALWAYS preview first!
[user@host ~]$ ls *.tmp
file1.tmp  file2.tmp  temp.tmp
[user@host ~]$ rm *.tmp          # Now delete (confirmed)

# echo shows expansion without executing
[user@host ~]$ echo rm *.tmp
rm file1.tmp file2.tmp temp.tmp

# Match 4-digit year pattern
[user@host ~]$ ls report_[0-9][0-9][0-9][0-9].pdf
Best practice: Before rm with wildcards, run ls with the same pattern to see exactly what matches.

Brace Expansion

Brace expansion generates multiple strings. Unlike wildcards, it does not match existing files — it creates new strings.

# Create multiple directories at once
[user@host ~]$ mkdir -p project/{src,docs,tests,build}

# Create numbered directories
[user@host ~]$ mkdir chapter{1..5}

# Create backup with date suffix
[user@host ~]$ cp config.txt{,.bak}
# Expands to: cp config.txt config.txt.bak

# Create multiple files with pattern
[user@host ~]$ touch file{a..e}.txt

# Nested expansion — creates 9 directories
[user@host ~]$ mkdir -p {dev,staging,prod}/{app,db,cache}

Working with Hidden Files

Files starting with a dot (.) are hidden — they do not appear in normal ls output and wildcards do not match them by default.
# Show hidden files with ls -a
[user@host ~]$ ls -a
.  ..  .bashrc  .bash_history  Documents  file.txt

# Wildcard * does NOT match hidden files
[user@host ~]$ ls *
Documents  file.txt

# Copy all contents including hidden files
[user@host ~]$ cp -r source/. destination/
# Trailing /. copies contents including hidden files

# Safe pattern for hidden files (excludes . and ..)
[user@host ~]$ rm -rf .[!.]*
# Safer: .[!.]* excludes . and ..
Caution: rm -rf .* may match .. (the parent directory). Use .[!.]* to safely target dot files.

Practical File Organization

# Create a project structure in one command
[user@host ~]$ mkdir -p myproject/{src,docs,tests,config}
[user@host ~]$ touch myproject/src/{main,utils,config}.py
[user@host ~]$ touch myproject/docs/{README,INSTALL,CHANGELOG}.md

# Organize downloads by file extension
[user@host Downloads]$ mkdir -p images documents archives
[user@host Downloads]$ mv *.jpg *.png *.gif images/
[user@host Downloads]$ mv *.pdf *.doc *.docx documents/
[user@host Downloads]$ mv *.zip *.tar.gz *.rar archives/

Practical Organization — Archives & Cleanup

# Archive old logs by date
[user@host logs]$ mkdir -p archive/2024/{01..12}
[user@host logs]$ mv access.log.2024-01-* archive/2024/01/

# Clean up temporary files anywhere in tree
[user@host ~]$ find . -name "*.tmp" -delete
[user@host ~]$ find . -name "*~" -delete  # Editor backup files
Tip: Consistent organization saves time. Create standard directory structures for projects and stick to them.
The find command with -delete is powerful for cleanup — it finds files matching patterns anywhere in the directory tree and removes them in one pass.

Common Mistakes

File operations can cause unrecoverable data loss. Know the common mistakes and how to prevent them.

MistakeResultPrevention
rm -rf / important (space typo)Deletes root filesystem!Tab completion; no spaces in paths
mv * .. in wrong directoryFiles moved to wrong parentUse pwd first; use absolute paths
cp file1 file2 where file2 existsfile2 silently overwrittenUse cp -i or check first
rm *.txt in wrong directoryDeletes wrong filesRun ls *.txt first; verify with pwd
Wildcard with space: rm * .txtDeletes ALL files plus ".txt"No space in pattern; use quotes if needed

Commands Summary

CommandPurposeKey Options
touchCreate empty file / update timestamp(rarely needs options)
mkdirCreate directories-p create parents
cpCopy files and directories-r recursive, -i interactive, -a archive
mvMove / rename files and directories-i interactive, -n no-clobber, -v verbose
rmRemove files-r recursive, -i interactive, -f force
rmdirRemove empty directories-p remove parents too
Wildcards
* any chars   ? one char   [abc] set   [a-z] range
Brace Expansion
{a,b,c} list   {1..10} range   {a..z} sequence

Best Practices — Do

Do

  • Use pwd before destructive operations
  • Preview wildcards with ls before rm
  • Use -i for interactive confirmation
  • Use tab completion to avoid typos
  • Use -v for verbose output when unsure
  • Back up before major changes
  • Use absolute paths for critical operations
  • Double-check rm -rf commands

Best Practices — Do Not

Do Not

  • Run rm -rf without verification
  • Use wildcards without previewing
  • Assume you know your current directory
  • Ignore overwrite warnings
  • Type paths without tab completion
  • Delete files you might need later
  • Skip backups before risky operations
  • Use -f routinely (defeats safeguards)
Professional habit: Think before you type. Verify before you execute. Especially with rm.

Key Takeaways

1

Create: touch for files, mkdir -p for directories. Use brace expansion for multiple items.

2

Copy: cp for files, cp -r for directories. Use -a to preserve everything.

3

Move/Rename: mv relocates and renames. Original is gone — destination is it.

4

Delete: rm for files, rm -r for directories. Permanent! Always verify first.

5

Organize: Wildcards (* ? []) match files. Braces ({}) generate strings.

Graded Lab

  • Create a project directory structure with subdirectories
  • Copy files between directories, preserving attributes
  • Move and rename files and directories
  • Use wildcards to copy/move groups of files
  • Practice safe deletion with ls preview and rm -i
  • Organize files by type using wildcards

Next: Editing Text Files