|

Linux CLI 6 🐧 make directory, copy, move, rename, delete files and directories

These are the core file management commands in Linux. They let you create, copy, move, rename, and delete files and directories from the command line.


Make and Delete Directories

mkdir d1 
mkdir d2 d3
mkdir -p d4/d5/d6
mkdir -m 750 d7
ls -la
rm d7 -r
CommandDescription
mkdir d1Create a single directory named d1
mkdir d2 d3Create multiple directories at once
mkdir -p d4/d5/d6Create nested directories (creates parents if needed)
mkdir -m 750 d7Create a directory with specific permissions
rm d7 -rDelete a directory recursively

mkdir — Make Directory

OptionDescription
(none)Create one or more directories
-pCreate parent directories as needed (no error if exists)
-m MODESet permissions (e.g., 750)
-vVerbose — show each directory created

Examples:

# Single directory
mkdir projects

# Multiple directories
mkdir photos videos music

# Nested directories with -p
mkdir -p work/projects/2024
# Creates: work/, work/projects/, work/projects/2024/
# No error if they already exist

# Specific permissions (rwxr-x---)
mkdir -m 750 private

# Verbose output
mkdir -v docs
# mkdir: created directory 'docs'

Permission modes:

ModeMeaning
755rwxr-xr-x (owner: all, others: read+execute)
700rwx—— (owner only)
750rwxr-x— (owner: all, group: read+execute, others: none)
777rwxrwxrwx (everyone: all)

rm — Remove

OptionDescription
(none)Remove files (not directories)
-rRecursive — remove directories and their contents
-fForce — ignore nonexistent files, no prompts
-iInteractive — prompt before each removal
-vVerbose — show what’s being removed
-dRemove empty directories (alternative to rmdir)

Examples:

# Delete a single file
rm file.txt

# Delete multiple files
rm file1.txt file2.txt file3.txt

# Delete with wildcard
rm *.tmp

# Delete a directory recursively
rm -r mydir

# Force delete (no prompt)
rm -rf mydir

# Interactive mode (prompts before each)
rm -i *.txt
# rm: remove regular file 'file1.txt'? y
# rm: remove regular file 'file2.txt'? n

# Verbose mode
rm -v *.log
# removed 'app.log'
# removed 'error.log'

⚠️ Warning: rm -rf / would destroy your system! Always double-check before using -rf.


Copy Files and Directories

cp file1.txt newfile.txt
cp -r d1 newd1
cp -p newfile.txt newfile2.txt
CommandDescription
cp file1.txt newfile.txtCopy file1.txt to newfile.txt
cp -r d1 newd1Copy directory d1 and its contents to newd1
cp -p newfile.txt newfile2.txtCopy preserving ownership, permissions, timestamps

cp — Copy

OptionDescription
(none)Copy a single file
-r or -RRecursive — copy directories and their contents
-pPreserve ownership, permissions, timestamps
-t DIRCopy into target directory
-aArchive — recursive + preserve all attributes
-uUpdate — copy only if source is newer or target doesn’t exist
-vVerbose — show what’s being copied
-iInteractive — prompt before overwriting
-nNo clobber — never overwrite existing files

Examples:

# Copy a file
cp notes.txt backup.txt

# Copy multiple files into a directory
cp file1.txt file2.txt file3.txt ~/backup/

# Copy with -t (target directory)
cp -t ~/backup/ file1.txt file2.txt

# Copy a directory recursively
cp -r projects ~/backup/projects

# Copy preserving attributes
cp -p notes.txt archive/notes.txt

# Archive mode (most complete copy)
cp -a projects ~/backup/projects

# Update mode (only copy newer files)
cp -u *.txt ~/backup/

# Verbose copy
cp -v *.txt ~/backup/
# 'file1.txt' -> '/home/kronos/backup/file1.txt'
# 'file2.txt' -> '/home/kronos/backup/file2.txt'

# Interactive copy (asks before overwrite)
cp -i notes.txt backup.txt
# cp: overwrite 'backup.txt'? y

Copy into same directory with new name:

cp file.txt file-copy.txt

Copy directory contents (not the directory itself):

cp -r source/. destination/
# Note the /. — copies contents, not the folder

Move and Rename Files

mv d1 d2
mv file1.txt d3/file2.txt
mv file1.txt file2.txt
mv -i file2.txt file.txt
rm file.txt
CommandDescription
mv d1 d2Move directory d1 into d2 (or rename if d2 doesn’t exist)
mv file1.txt d3/file2.txtMove file to d3 with a new name
mv file1.txt file2.txtRename file1.txt to file2.txt
mv -i file2.txt file.txtMove with interactive prompt before overwrite
rm file.txtDelete a file

mv — Move / Rename

OptionDescription
(none)Move or rename
-iInteractive — prompt before overwriting
-fForce — overwrite without prompting
-nNo clobber — never overwrite
-vVerbose — show what’s being moved
-uUpdate — move only if source is newer
-t DIRMove into target directory

Examples:

# Rename a file
mv oldname.txt newname.txt

# Move a file into a directory
mv notes.txt ~/Documents/

# Move with a new name
mv notes.txt ~/Documents/important-notes.txt

# Move multiple files into a directory
mv *.txt ~/Documents/

# Move with -t (target directory)
mv -t ~/Documents/ file1.txt file2.txt

# Rename a directory
mv old-folder new-folder

# Move a directory into another
mv projects ~/backup/

# Interactive move
mv -i source.txt dest.txt
# mv: overwrite 'dest.txt'? y

# No clobber (never overwrite)
mv -n source.txt dest.txt

# Verbose move
mv -v *.log ~/logs/
# 'app.log' -> '/home/kronos/logs/app.log'
# 'error.log' -> '/home/kronos/logs/error.log'

Key insight: mv uses the destination to decide whether to move or rename:

  • If destination is an existing directory → moves into it
  • If destination is a new name → renames
# If "docs" exists as a directory:
mv file.txt docs/        # Moves into docs/

# If "new.txt" doesn't exist:
mv file.txt new.txt      # Renames to new.txt

Complete Example Session

# ============================================
# PART 1: CREATING DIRECTORIES
# ============================================

# Create a single directory
$ mkdir projects
$ ls
projects

# Create multiple directories
$ mkdir photos videos music
$ ls
music  photos  projects  videos

# Create nested directories
$ mkdir -p work/2024/january
$ ls -R work
work:
2024

work/2024:
january

work/2024/january:

# Create with specific permissions
$ mkdir -m 700 private
$ ls -la private
drwx------ 2 kronos users 4096 Jan 15 10:30 private

# Verbose creation
$ mkdir -v docs
mkdir: created directory 'docs'

# ============================================
# PART 2: COPYING
# ============================================

# Create a test file
$ echo "Hello" > file1.txt

# Copy a file
$ cp file1.txt file2.txt
$ ls
file1.txt  file2.txt

# Copy with new name
$ cp file1.txt backup.txt
$ ls
backup.txt  file1.txt  file2.txt

# Copy multiple files into a directory
$ mkdir backups
$ cp file1.txt file2.txt backups/
$ ls backups/
file1.txt  file2.txt

# Copy a directory recursively
$ mkdir -p source/sub
$ echo "content" > source/sub/data.txt
$ cp -r source source-copy
$ ls -R source-copy
source-copy:
sub

source-copy/sub:
data.txt

# Copy preserving attributes
$ cp -p file1.txt preserve.txt
$ ls -la file1.txt preserve.txt
-rw-r--r-- 1 kronos users 6 Jan 15 10:30 file1.txt
-rw-r--r-- 1 kronos users 6 Jan 15 10:30 preserve.txt
# Same timestamps and permissions

# Verbose copy
$ cp -v file1.txt verbose-copy.txt
'file1.txt' -> 'verbose-copy.txt'

# ============================================
# PART 3: MOVING AND RENAMING
# ============================================

# Rename a file
$ mv file2.txt renamed.txt
$ ls
backup.txt  file1.txt  renamed.txt

# Move a file into a directory
$ mv file1.txt backups/
$ ls backups/
file1.txt  file2.txt

# Move with new name
$ mv backup.txt backups/old-backup.txt
$ ls backups/
backup.txt  file1.txt  file2.txt

# Rename a directory
$ mv docs documentation
$ ls
documentation  photos  projects  videos ...

# Move a directory
$ mv photos pictures-backup
$ ls
documentation  pictures-backup  projects  videos ...

# Move multiple files with wildcard
$ touch a.txt b.txt c.txt
$ mkdir text-files
$ mv *.txt text-files/
$ ls text-files/
a.txt  b.txt  c.txt

# Interactive move (prompts if destination exists)
$ echo "old" > original.txt
$ echo "new" > existing.txt
$ mv -i existing.txt original.txt
mv: overwrite 'original.txt'? y
$ cat original.txt
new

# No clobber (never overwrite)
$ echo "test1" > source.txt
$ echo "test2" > dest.txt
$ mv -n source.txt dest.txt
$ cat dest.txt
test2

# ============================================
# PART 4: DELETING
# ============================================

# Delete a file
$ rm renamed.txt
$ ls
backup.txt  file1.txt  projects  ...

# Delete multiple files
$ touch temp1.tmp temp2.tmp temp3.tmp
$ rm temp1.tmp temp2.tmp
$ ls temp*.tmp
temp3.tmp

# Delete with wildcard
$ rm *.tmp
$ ls *.tmp
ls: cannot access '*.tmp': No such file or directory

# Interactive delete
$ touch important.txt
$ rm -i important.txt
rm: remove regular file 'important.txt'? y

# Delete a directory (must be empty without -r)
$ mkdir emptydir
$ rm emptydir
rm: cannot remove 'emptydir': Is a directory
$ rm -r emptydir

# Force delete a directory
$ mkdir -p full/nested
$ touch full/nested/file.txt
$ rm -rf full
$ ls full
ls: cannot access 'full': No such file or directory

# Verbose delete
$ touch log1.log log2.log
$ rm -v *.log
removed 'log1.log'
removed 'log2.log'

Quick Reference

mkdir Options

OptionDescription
-pCreate parents as needed
-m MODESet permissions
-vVerbose

cp Options

OptionDescription
-rRecursive (directories)
-pPreserve attributes
-aArchive (recursive + preserve)
-uUpdate (newer only)
-vVerbose
-iInteractive
-nNo clobber
-t DIRTarget directory

mv Options

OptionDescription
-iInteractive
-fForce overwrite
-nNo clobber
-vVerbose
-uUpdate
-t DIRTarget directory

rm Options

OptionDescription
-rRecursive (directories)
-fForce (no prompts)
-iInteractive
-vVerbose
-dRemove empty directories

Common Patterns

TaskCommand
Copy file to backupcp file.txt file.txt.bak
Copy directory treecp -a source/ dest/
Copy only newer filescp -u *.txt backup/
Move multiple filesmv *.jpg ~/Photos/
Rename filemv old.txt new.txt
Rename extensionmv file.txt file.md
Rename directorymv olddir newdir
Delete empty directoryrmdir dir or rm -d dir
Delete directory + contentsrm -r dir
Force delete directoryrm -rf dir
Interactive safe deleterm -i *.txt
Batch renameUse a loop (or rename command)

Best Practices

Do This:

# Always verify before deleting
ls *.log            # Check first
rm *.log            # Then delete

# Use -i for safety on important files
rm -i important.txt

# Use -n to prevent accidental overwrites
cp -n source.txt dest.txt
mv -n source.txt dest.txt

# Use -v to see what's happening
cp -v *.txt backup/
mv -v *.jpg ~/Photos/

# Use quotes for filenames with spaces
cp "my file.txt" "my file backup.txt"

# Test mkdir -p with dry-run mentality
mkdir -p project/src/components

# Copy directories with trailing slash carefully
cp -r source/ dest/     # Copy contents
cp -r source dest/      # Copy directory itself

Don’t Do This:

# Don't rm -rf without checking
rm -rf /important       # ❌ Dangerous!

# Don't use rm * carelessly
rm *                    # ❌ Deletes everything

# Don't forget -r for directories
rm mydir                # ❌ "Is a directory" error

# Don't overwrite without checking
cp new.txt important.txt  # ❌ Silently overwrites
cp -i new.txt important.txt  # ✅ Prompts

# Don't move files without checking destination
mv *.txt /tmp/          # ⚠️ Where do they go?

# Don't forget quotes for filenames with spaces
cp my file.txt backup/  # ❌ Shell splits this
cp "my file.txt" backup/  # ✅ Correct

# Don't use rm -rf on unknown paths
rm -rf $UNSET_VARIABLE/  # ❌ If $UNSET is empty, rm -rf /

Common Pitfalls

PitfallProblemSolution
rm -rf /Destroys systemNever use / as target
rm -rf *Deletes everything in current dirVerify with ls first
Spaces in filenamesShell splits argumentsQuote: "my file.txt"
mv overwrites silentlyLoses original fileUse -i or -n
cp without -r for dirsError: omitting directoryAdd -r
mkdir fails on existing dirError messageUse -p (no error if exists)
Forgetting trailing slashWrong copy behaviorcp -r src/ dest/ vs cp -r src dest/

Trailing Slash Matters (cp and mv)

CommandBehavior
cp -r source destCreates dest/source/ if dest exists
cp -r source/ destCopies contents of source into dest
cp -r source/. destCopies contents and hidden files

Example:

# If source/ contains a.txt, b.txt
cp -r source dest/       # → dest/source/a.txt, dest/source/b.txt
cp -r source/ dest/      # → dest/a.txt, dest/b.txt

Visual: Common Operations

CREATE:                          DELETE:
mkdir newdir                     rm file.txt
mkdir -p a/b/c                   rm -r dir
mkdir -m 700 private             rm -rf dir

COPY:                            MOVE / RENAME:
cp file.txt copy.txt             mv old.txt new.txt
cp -r dir1 dir2                  mv file.txt ~/docs/
cp -a dir1 dir2                  mv dir1 dir2

                                  (If dir2 exists → moves into it)
                                  (If dir2 doesn't exist → renames)

Real-World Examples

1. Project Setup

mkdir -p myproject/{src,tests,docs}
cd myproject
touch README.md

2. Backup Before Editing

cp -p important.conf important.conf.bak
# Edit important.conf
# If something breaks:
# mv important.conf.bak important.conf

3. Organize Downloads

mkdir -p ~/Downloads/{images,videos,documents,archives}
mv ~/Downloads/*.jpg ~/Downloads/images/
mv ~/Downloads/*.mp4 ~/Downloads/videos/
mv ~/Downloads/*.pdf ~/Downloads/documents/
mv ~/Downloads/*.zip ~/Downloads/archives/

4. Archive and Clean

# Create backup
cp -a project project-backup-$(date +%Y%m%d)

# Clean temp files
rm -v *.tmp *.log

5. Rename Extensions

# Rename all .htm to .html
for f in *.htm; do mv "$f" "${f%.htm}.html"; done

6. Safe Delete with Confirmation

# Interactive delete of all logs
rm -i /var/log/*.log

Summary

CommandPurposeExample
mkdirCreate directoriesmkdir -p a/b/c
cpCopy files/directoriescp -r src/ dest/
mvMove or renamemv old.txt new.txt
rmDelete files/directoriesrm -rf dir
rmdirDelete empty directoriesrmdir emptydir

Key takeaways:

  • mkdir -p creates nested directories safely (no error if exists)
  • cp -r copies directories — without -r, you get an error
  • cp -a is the safest way to copy directories with all attributes
  • mv handles both move and rename — destination decides which
  • rm -r deletes directories and their contents
  • rm -rf force deletes without prompts — use with extreme caution
  • -i makes commands interactive — prompts before overwriting/deleting
  • -v shows what’s happening — great for learning and debugging
  • Trailing slashes matter with cp and mv

Remember: With great power comes great responsibility. Commands like rm -rf can destroy data instantly with no undo. Always test with ls first, use -i for safety, and never use rm -rf on a path you’re not 100% sure about!


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!