Copying and Moving
Two commands handle most file manipulation in Linux: cp for copying and mv for moving. They work similarly, but the difference matters.
cp – Copy Files
What it does: Creates a duplicate of a file. The original stays exactly where it is.
cp file.txt backup.txt
This copies file.txt and names the copy backup.txt. Both files now exist.
Try it now: Type the following:
cp ~/projects/my-app/README.md ~/projects/my-app/README.backup
Now run ls ~/projects/my-app/README* – you’ll see both the original and the backup.
Copying Directories
To copy a directory and everything inside it, you need the -r flag (recursive):
cp -r dir/ backup/
Without -r, you’ll get an error. The command needs to be told explicitly to go into the directory and copy everything inside it.
Try it now:
cp -r ~/projects/my-app/src ~/projects/my-app/src-backup
Run ls ~/projects/my-app/ to confirm the backup directory was created.
You'll see
-r (or -R) a lot in Linux. It stands for "recursive," meaning "do this to the directory AND everything inside it." Many commands need this flag to work on directories.
mv – Move and Rename Files
What it does: Moves a file to a new location, or renames it. Unlike cp, the original is gone – the file now only exists in the new location (or with the new name).
Renaming a File
mv old.txt new.txt
The file old.txt no longer exists. It’s been renamed to new.txt.
Moving a File to a Different Directory
mv file.txt Documents/
This takes file.txt out of the current directory and puts it inside Documents/.
Try it now:
mv ~/Downloads/data.csv ~/Documents/
Check with ls ~/Documents/ – the file should be there. Check ls ~/Downloads/ – it should be gone from there.
Moving vs. Copying
The difference is simple but important:
| Command | Original file? | New file? |
|---|---|---|
cp file.txt copy.txt |
Still exists | Created |
mv file.txt new.txt |
Gone | Created (same file, new name/location) |
Think of cp as a photocopier and mv as physically picking something up and placing it somewhere else.
When AI Tools Use These Commands
Your AI coding assistant uses cp and mv regularly. Here are common scenarios:
- Creating backups before making changes:
cp config.json config.json.bak - Restructuring a project:
mv src/components/old-name.js src/components/new-name.js - Organizing generated files:
mv output/*.csv ~/Documents/reports/
When you see your AI tool run these commands, you now know exactly what’s happening: it’s either making a copy (safe, the original stays) or moving/renaming (the original is gone from its old location).
cp file.txt backup.txt -- copy a filecp -r dir/ backup/ -- copy a directorymv old.txt new.txt -- rename a filemv file.txt Documents/ -- move a file to another directory
Practice
Try these commands in the terminal:
cp ~/projects/my-app/package.json ~/projects/my-app/package.json.bak– back up a config filemv ~/projects/my-app/package.json.bak ~/Documents/– move the backup to Documentsls ~/Documents/package.json.bak– confirm it arrived