Working with files and folders
Now let's create, copy, move, rename and delete. These are the everyday file operations you'll use constantly.
Creating folders and files
| Command | Does |
|---|---|
mkdir name |
Make a directory |
mkdir -p a/b/c |
Make nested folders, including any missing parents |
touch file |
Create an empty file (or update its timestamp) |
echo "text" > file |
Create a file with content (more on > in the Pipes lesson) |
Copying: cp
cp source destinationcopies a file.cp file folder/copies it into a folder, keeping the name.cp -rcopies a folder and everything inside it (recursively).
Moving and renaming: mv
There's no separate "rename" command. Renaming is moving to a new name:
mv old newrenames.mv file folder/moves it into a folder.mv a.txt b.txt docs/moves several files at once.
Deleting: rm and rmdir
| Command | Deletes |
|---|---|
rm file |
A file |
rm file1 file2 |
Several files |
rmdir folder |
An empty folder |
rm -r folder |
A folder and everything inside it |
rm -rf folder |
The same, with no questions or errors (force) |
⚠️ There is no recycle bin in the terminal.
rmdeletes permanently. Double-check the path before runningrm -r, and never run commands likerm -rf /orrm -rf ~. (The simulator will stop you, but a real computer won't.) Userm -ito be asked before each deletion.
Overwriting: a silent danger
cp and mv overwrite existing files without asking:
Use cp -i and mv -i (interactive) to be prompted first, or -n to never overwrite.
Practice: organise your Downloads
The ~/Downloads folder is a mess. Organise it:
- Create the folders
imagesanddocumentsinsideDownloads. - Move the
.jpgand.pngfiles intoimages. - Move
report.pdfintodocuments. - Delete
installer.dmg. - Show the result with
tree Downloads.
✎ Check your understanding
1.How do you rename old.txt to new.txt?
2.Which command deletes a folder that still has files in it?