Working with Files and Directories
Prerequisites: Navigating the file system
These commands create, copy, move, and delete files and folders.
Creating
mkdir reports
mkdir -p archive/2025/april
touch notes.txt todo.txt
ls
archive
notes.txt
reports
todo.txt
mkdircreates a directory;-pcreates all the missing parents and doesn't complain if it already exists.touchcreates empty files (or updates the timestamp of existing ones).
Copying, moving, and renaming
echo "draft" > report.txt
cp report.txt report-backup.txt
mv report.txt final-report.txt
mkdir docs
mv final-report.txt docs/
cp -r docs docs-copy
ls
ls docs-copy
docs
docs-copy
report-backup.txt
final-report.txt
cp source destinationcopies;cp -rcopies a directory and everything in it.mvmoves and renames — renaming is just moving to a new name.
Deleting
touch old.txt
mkdir -p tmp/cache
rm old.txt
rm -r tmp
ls
echo "done"
done
rm deletes files; rm -r deletes a directory and everything inside it.
rmdir removes only empty directories.
There is no undo
Deleted files don't go to a trash can. Be especially careful with rm -r
and wildcards, and never run a command like rm -rf on a path you haven't
double-checked. Two safety habits:
- Use
rm -i, which asks before each deletion, while you're learning. - Run
lswith the same pattern first to see exactly what would be deleted.
cp and mv also silently overwrite existing files; -i makes them
ask first, and -n makes them never overwrite.
Practice
Create a folder photos with subfolders 2024 and 2025, create an empty
file beach.jpg in 2024, then move it to 2025.
Show solution
mkdir -p photos/2024 photos/2025
touch photos/2024/beach.jpg
mv photos/2024/beach.jpg photos/2025/
ls photos/2025
beach.jpg