Loading

T6 Linux and Bash · Lesson 3

Files and folders

The everyday work on files: making files and folders, reading them whole or in part, copying, moving and renaming, removing with care when there is no bin, naming many files with one pattern, finding files anywhere below a folder, and packing a folder into one archive.

  • make files and folders, and remove empty folders
  • read a file whole, or only its start or its end
  • copy, move and rename files and folders, and pack them into an archive
  • remove files and folders safely, looking before you act
  • name many files at once with patterns, and stop a pattern with quotes
  • find files by name, kind, size and age, and act on what you find
About 50 minutesChecked against GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-06); GNU coreutils on the laptop (installed beside Ubuntu 26.04's default uutils; the kit's sandbox uses GNU's) 9.7 (2026-11-06)Play this lesson's games

The back cover

A shop keeps its goods in boxes on shelves, and the work never stops: new boxes, copies, moves, and old stock thrown out. On a computer the boxes are files and the shelves are folders, and a few short commands do all of that work.

These pages show how to make files and folders, and how to read them whole or in part. They show how to copy, move and rename, and how to remove with care when there is no bin. They show patterns that name many files at once, and find, which searches a whole tree.

Before you start

The story: No bin down here

The Underway's stores are a wall of numbered crates and folders of records, and they are a mess: copies of copies, names with spaces in them, last year's pump logs mixed with this year's. Corin was told to clear out the old logs. He said one short command, and it did exactly what he said.

This year's logs went with them. There is no bin in the Underway, and nothing that is removed comes back.

Warden Rao looks at the empty shelf for some time. "The tunnels did what he told them," she says. "So we will learn to say it carefully, and we will look before we say it."

You can speak to the shell, and you can find your way around the tree. This lesson is about the work itself: making files and folders, reading them, copying, moving, removing, and finding them again. Most of a day at a terminal is made of these few commands.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Paths.logs/2026-01.logEvery command here takes them.
The parent folder...A copy can go anywhere you can name.
Hidden names.ls -aPatterns skip them too.
Quotes."crate list.txt"They also stop patterns.
Tab.It finishes a nameUse it before every rm.
The up arrow.It brings back a commandLook with ls, then change it to rm.
The exit status.echo $?Each command here reports one.
Joining with &&.mkdir x && cd xMake a thing, then use it.
The long listing.ls -lIt checks sizes after a copy.
find.find . -name gauge.txtIt learns many more tests.

By the end of this lesson you will be able to:

  • make files and folders, and remove empty folders;
  • read a file whole, or only its start or its end;
  • copy, move and rename files and folders, and pack them into an archive;
  • remove files and folders safely, looking before you act;
  • name many files at once with patterns, and stop a pattern with quotes;
  • find files by name, kind, size and age, and act on what you find.

How to follow this lesson

Each block starts afresh in its own small folder, so removing something in one block cannot touch the next. That makes this page the safest place there is to practise rm. On a real machine, what you remove does not come back.

In one line

This lesson teaches the everyday work on files: make, read, copy, move, remove and find them, and say many names in one short pattern.

Making files and folders

At a glance

A new store room needs shelves before it needs boxes. On a computer the shelves are folders, and the boxes are files.

The command mkdir makes a folder, and mkdir -p makes a whole chain of folders at once, without complaint when they already exist. The command touch makes an empty file, or gives a file that exists a new time. The command rmdir removes a folder, but only an empty one, so it can never take anything with it. None of them prints anything when it works.

Take a guess: Can a disk refuse a new empty file while it still has free space?

A new store room needs shelves before it needs boxes. On a computer the shelves are folders, and the boxes are files. Two commands make them: mkdir makes folders, and touch makes empty files.

mkdir: make a folder

The name mkdir is short for make directory. It makes a folder for each name you give, and it prints nothing when it works:

mkdir north south east
ls
east  north  south

A new folder must go inside a folder that already exists. Asking for one inside a folder that is not there yet is an error:

mkdir stores/2026/january
mkdir: cannot create directory ‘stores/2026/january’: No such file or directory

The option -p, short for parents, makes every missing folder on the way. Add -v, for verbose, and mkdir says what it made:

mkdir -pv stores/2026/january
mkdir: created directory 'stores'
mkdir: created directory 'stores/2026'
mkdir: created directory 'stores/2026/january'

The option -p has a second use. Without it, mkdir complains when the folder already exists. With it, mkdir stays quiet, because what you asked for is already true. That makes mkdir -p safe to run twice:

mkdir logs
mkdir logs
mkdir -p logs
echo $?
mkdir: cannot create directory ‘logs’: File exists
0

touch: make an empty file

The command touch makes an empty file for each name that does not exist yet. A file that already exists keeps its contents, and touch only sets its time to now. That is where its name comes from: it touches the file, and changes nothing inside.

touch notes.txt list.txt
ls -l
total 0
-rw-rw-r-- 1 asha asha 0 Jan  1 10:00 list.txt
-rw-rw-r-- 1 asha asha 0 Jan  1 10:00 notes.txt

Both files are 0 bytes, as nothing has been written in them. To put a line of text in a file, you can send echo's output into it with the sign >. The next lesson explains it fully. For now, read it as into:

echo "pump one" > notes.txt
cat notes.txt
ls -l notes.txt
pump one
-rw-rw-r-- 1 asha asha 9 Jan  1 10:00 notes.txt

The file holds the 8 letters and space of pump one, then the end of the line: 9 bytes.

rmdir: remove an empty folder

The command rmdir removes a folder, but only an empty one. That is a safety feature: it cannot take anything with it.

mkdir empty full
touch full/crate.txt
rmdir empty
rmdir full
ls
rmdir: failed to remove 'full': Directory not empty
full
CommandIt doesIt prints when it works
mkdir namemakes a foldernothing
mkdir -p a/b/cmakes the whole chain, and is quiet if it existsnothing
mkdir -v namemakes a folder, and says socreated directory
touch namemakes an empty file, or updates its timenothing
rmdir nameremoves an empty foldernothing

Worked example 1

Warden Rao wants the store laid out: a folder named stores, holding a folder for 2025 and one for 2026, each with a folder named january inside, and an empty file named index.txt in stores. Make it with two commands, and check it.

What we have: the layout, and the commands mkdir -p and touch

What we need: the folders and the file, made and checked

The plan: one mkdir -p can make both chains, as it takes several paths; touch makes the file; tree shows the result

mkdir -p stores/2025/january stores/2026/january
touch stores/index.txt
tree stores
stores
├── 2025
│   └── january
├── 2026
│   └── january
└── index.txt

5 directories, 1 file
  1. The command mkdir made stores once, and both chains below it. The command tree counts five folders, as it counts stores itself.

Two commands make the whole layout.

Check: the drawing shows two years, each with a january, and index.txt beside them.

A path that fails: writing mkdir stores/2025/january with no -p. Neither stores nor 2025 exists yet, so mkdir stops with No such file or directory.

When you are stuck: mkdir or touch does not do what you expected

No such file or directory, from mkdir: a folder on the way is missing. Add -p.

File exists: the name is taken. Choose another, or use -p if the folder is what you wanted anyway.

The command touch seemed to do nothing: the file existed, so only its time changed.

Directory not empty, from rmdir: look inside with ls first.

Your turn

mkdir -p a/b
mkdir -p a/b
ls a
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b
  1. The first line makes a, then b inside it.
  2. The second line finds both there, and -p keeps it quiet.
  3. ls a lists what is inside a.

It prints b.

Which one command makes the folders pumps, pumps/north and pumps/south?Tap to reveal
  1. mkdir takes several paths.
  2. -p makes pumps on the way.

mkdir -p pumps/north pumps/south.

A file named log.txt holds three lines. You run touch log.txt. What happens to the lines?Tap to reveal
  1. touch only makes files that are missing.
  2. For a file that exists, it sets the time.

Nothing: the lines stay, and only the file's time changes.

Did you know?

Full, with space to spare

A disk can refuse a new file while it still has free space. Each file has an inode, a record of its owner, permissions, times and place on the disk, so an empty file made by touch needs one too. On the ext4 file system, mke2fs makes one inode for every so many bytes when the disk is formatted. That ratio cannot be changed afterwards, and df -i shows how many inodes are left.

Why it fits here: It answers this topic's question: every file, even an empty one, needs an inode, and a disk holds a fixed share of them.

Sources: Linux man-pages: inode(7); GNU Coreutils manual: df invocation; Linux man-pages: mke2fs(8)

A date parser from 1990

touch can set a file's time from plain words. The GNU manual says that its -d option can read month names, time zones, am and pm, and even the word yesterday. The code that reads such dates began as getdate, written by Steven M. Bellovin at the University of North Carolina at Chapel Hill. Rich $alz and Jim Berets overhauled it in August 1990.

Why it fits here: It shows how this topic's touch reads a date: plain words like yesterday work, through a parser that dates from 1990.

Sources: GNU Coreutils manual: touch invocation; GNU Coreutils manual: Relative items in date strings; GNU Coreutils manual: Authors of parse_datetime

In one line

mkdir makes folders, and -p makes a whole chain and is quiet when it already exists. touch makes an empty file, or updates the time of one that exists. rmdir removes a folder only when it is empty.

Looking inside files

At a glance

Before you change a file, you want to see what is in it. A shop's register is read in different ways: every page, the first few entries, or only today's, at the end.

The command cat prints a whole file, and cat -n numbers its lines. The commands head and tail print the first or the last 10 lines, or as many as -n says, and tail -f keeps watching a growing file. The command wc counts lines, words and bytes, and less shows a long file one screen at a time.

Take a guess: Why would a program for reading long files be named less?

Before you change a file, you want to see what is in it. Think of a register at a shop counter. Sometimes you read every page, sometimes only the first few entries, and sometimes only today's, at the end. The shell has a command for each.

cat: the whole file

The command cat prints a whole file. Give it two files, and it prints one after the other. Its name comes from concatenate, which means joining things end to end:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cat logs/2026-01.log
cat logs/2025-01.log logs/2026-02.log
pump one ok
pump two slow
pump one ok
all clear

The option -n numbers the lines, which helps when someone tells you that the problem is on line 2:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cat -n notes.txt
     1	pump one
     2	pump two
     3	valve

head and tail: the start and the end

A log can be thousands of lines long, and cat would scroll all of them past you. The command head prints the first lines of a file, and tail the last. Each prints 10 lines unless you say otherwise with -n:

seq prints the numbers 1 to 100, and > puts them in a file

seq 1 100 > counts.txt
head -n 3 counts.txt
tail -n 2 counts.txt
1
2
3
99
100

The command tail has one more form worth knowing. With a plus sign, tail -n +2 means from line 2 to the end, which skips a heading line:

printf writes three lines, and > puts them in a file

printf 'name,pumps\nnorth,3\nsouth,2\n' > pumps.csv
tail -n +2 pumps.csv
north,3
south,2

On a server, tail -f is a favourite. It prints the end of a log, then keeps watching and prints each new line as it is written, until you press Ctrl+C. It never ends by itself, so it needs a real terminal.

wc: how much

You met wc in the first lesson. It counts lines, words and bytes, and with several files it adds a total:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

wc -l logs/2025-01.log logs/2026-01.log
 1 logs/2025-01.log
 2 logs/2026-01.log
 3 total

less: a long file, one screen at a time

For a file too long to read at once, less shows one screen at a time. It is the same reader that shows manual pages, with the same keys: Space for the next screen, b for back, / to search, and q to quit. It takes over the window, so it has no Run button here:

In a real terminal, this opens the file for reading, and q leaves

less counts.txt
You wantType
the whole filecat file
it with line numberscat -n file
the first 10 lineshead file
the last 3 linestail -n 3 file
everything after a heading linetail -n +2 file
to keep watching the endtail -f file
to read a long fileless file
to count the lineswc -l file

Worked example 2

A pump log has a reading on each line. Warden Rao wants to know how many readings there are, what the first one was, and what the last two were.

What we have: a file named pump.log, with one reading on each line

What we need: a count, the first line and the last two lines

The plan: wc -l counts the lines; head -n 1 takes the first; tail -n 2 takes the last two

In a folder with pump.log

wc -l pump.log
head -n 1 pump.log
tail -n 2 pump.log
12 pump.log
reading 1: 40
reading 11: 50
reading 12: 51
  1. None of the three commands changed the file. They only read it.

There are 12 readings; the first is 40, and the last two are 50 and 51.

Check: the last line is reading 12, which matches the count of 12 lines.

A path that fails: using cat and counting by eye. On 12 lines that works, slowly; on 12,000 the lines scroll past, and you count wrongly.

When you are stuck: a file is hard to read in the terminal

It scrolls past too fast: use head, tail, or less.

You need one line of it: cat -n shows the numbers, and the next lesson shows how to pick lines out.

Strange symbols fill the screen: the file is not text, perhaps a picture. Press Ctrl+C if it goes on.

tail -f never ends: that is its job. Press Ctrl+C when you have seen enough.

Your turn

seq 1 5 > n.txt
head -n 2 n.txt
tail -n 1 n.txt
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1
2
5
  1. The file holds 1 to 5, one number a line.
  2. head -n 2 gives the first two lines.
  3. tail -n 1 gives the last line.

It prints 1, 2 and 5, each on its own line.

Which command prints a file from its 5th line to the end?Tap to reveal
  1. tail with a plus sign counts from the start.

tail -n +5 file.

You want to watch a server's log while new lines arrive. Which command, and how do you stop it?Tap to reveal
  1. tail -f keeps watching the end of a file.
  2. Ctrl+C stops a running command.

tail -f the log, then Ctrl+C.

Did you know?

A backwards more

The name less began as a joke. Mark Nudelman, its author, explains that in 1983 a company called Integrated Office Systems had enormous log files, and the pager more could not move backwards through them. The team said it needed a backwards more, and someone named it less. Nudelman wrote the first version in late 1983 and posted it to the newsgroup net.sources in May 1985.

Why it fits here: It answers this topic's question: less was named as a backwards more, a pager that could go back through long logs.

Source: Mark Nudelman: Frequently asked questions about less

Six characters, 18 bytes

wc can give two sizes for one word. The GNU manual says wc -c counts bytes and wc -m counts characters. The Hindi word नमस्ते is made of six Unicode characters, counting the small mark called the halant, and all six come from the Devanagari block, U+0900 to U+097F. UTF-8 stores each character from U+0800 to U+FFFF in three bytes, so wc -c counts 18 and wc -m counts 6.

Why it fits here: It shows that this topic's wc -c counts bytes, not letters: each character of a Hindi word takes three bytes.

Sources: GNU Coreutils manual: wc invocation; The Unicode Standard: Devanagari code chart; RFC 3629: UTF-8, a transformation format of ISO 10646

In one line

The command cat prints a whole file, and cat -n numbers its lines. The commands head and tail print the first or last lines, 10 unless -n says otherwise, and tail -f keeps watching. The command wc counts, and less reads a long file one screen at a time.

Copying and moving

At a glance

Copying makes a second file with the same contents. Moving takes the one file to a new place, or gives it a new name.

Both commands follow one pattern: the thing first, then where it goes. The command cp copies, and a folder needs cp -r. The command mv moves, and inside one folder it renames. Both replace a file of the same name without asking, unless you add -i. The command tar packs a whole folder into one archive, and gzip squeezes it smaller.

Take a guess: Why can moving a huge file take no time, while copying it takes minutes?

Copying makes a second file with the same contents. Moving takes the one file to a new place, or gives it a new name. Both commands follow one pattern: the thing first, then where it goes. Read them as copy this to there, and move this to there.

cp: copy

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cp notes.txt notes-copy.txt
ls
cat notes-copy.txt
logs  notes-copy.txt  notes.txt
pump one
pump two
valve

When the last name is a folder that exists, the copy goes inside it and keeps its own name. Several files can go into one folder at once:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

mkdir backup
cp notes.txt logs/2026-01.log backup
ls backup
2026-01.log  notes.txt

A folder needs -r, for recursive, which means the folder and everything inside it, all the way down. Without it, cp refuses:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cp logs logs-backup
cp -r logs logs-backup
ls logs-backup
cp: -r not specified; omitting directory 'logs'
2025-01.log  2025-02.log  2026-01.log  2026-02.log

A copy replaces without asking

This is the trap of cp. If the target file exists, cp writes over it, and the old contents are gone. There is no question and no message:

echo old > a.txt
echo new > b.txt
cp b.txt a.txt
cat a.txt
new

The option -i, for interactive, makes cp ask first. Answer y to replace the file, or n to keep it:

Typed: n, then Enter, at the question

asha@tower:~/shop$ cp -i b.txt a.txt
cp: overwrite 'a.txt'? n
asha@tower:~/shop$ cat a.txt
old
asha@tower:~/shop$ 

mv: move, and rename

The command mv works like cp, except that the original does not stay behind. Within one folder, moving a file to a new name renames it. That is the everyday way to rename on Linux:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

mv notes.txt notes-2026.txt
mkdir old
mv logs/2025-01.log logs/2025-02.log old
ls
ls old
logs  notes-2026.txt  old
2025-01.log  2025-02.log

The command mv moves a folder with everything in it, and needs no -r, because nothing is copied: the folder only gets a new place in the tree. Like cp, it replaces an existing file without asking, and it takes -i too.

You wantType
a copy with a new namecp a.txt b.txt
a copy inside a foldercp a.txt backup
a copy of a whole foldercp -r logs logs-backup
a new namemv a.txt b.txt
a file moved into a foldermv a.txt store
to be asked before anything is replacedcp -i or mv -i

Packing many files into one: tar and gzip

To send a folder to someone, or to keep a copy of it, you often want it as one file. The command tar packs files and folders into one file, called an archive. With -z it also squeezes the archive smaller, which is called compressing it. The small shell does not have tar, so this block shows a real terminal:

Terminal

asha@tower:~/shop$ tar -czf logs.tar.gz logs
asha@tower:~/shop$ ls
logs  logs.tar.gz  notes.txt
asha@tower:~/shop$ tar -tzf logs.tar.gz | sort
logs/
logs/2025-01.log
logs/2025-02.log
logs/2026-01.log
logs/2026-02.log
asha@tower:~/shop$ mkdir restore
asha@tower:~/shop$ tar -xzf logs.tar.gz -C restore
asha@tower:~/shop$ ls restore/logs
2025-01.log  2025-02.log  2026-01.log  2026-02.log

Read the letters as words. In -czf, c means create, z means compress, and f means that the next word is the archive's file name. Then t lists what is inside, and x extracts it again. The option -C restore unpacks into the folder restore. The | sort only puts tar's list in order; the next lesson explains it.

The ending .tar.gz says how the file was made: a tar archive, compressed by gzip. The command gzip can also compress a single file on its own, and gunzip undoes it:

Terminal

asha@tower:~/shop$ gzip notes.txt
asha@tower:~/shop$ ls
logs  notes.txt.gz
asha@tower:~/shop$ gunzip notes.txt.gz
asha@tower:~/shop$ cat notes.txt
pump one
pump two
valve

Worked example 3

Before anything is tidied, Warden Rao wants a full copy of the logs folder, named logs-copy. Then last year's two logs must move into a new folder named 2025, and notes.txt must be renamed notes-2026.txt.

What we have: the logs folder, its four logs, and notes.txt

What we need: a copy of logs, the old logs moved, and a file renamed

The plan: copy first, with -r as logs is a folder; make the new folder; move the two old logs into it; rename with mv

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cp -r logs logs-copy
mkdir 2025
mv logs/2025-01.log logs/2025-02.log 2025
mv notes.txt notes-2026.txt
ls
ls logs
ls logs-copy
2025  logs  logs-copy  notes-2026.txt
2026-01.log  2026-02.log
2025-01.log  2025-02.log  2026-01.log  2026-02.log
  1. The copy was made before anything moved, so logs-copy still holds all four logs. The folder 2025 is listed first, as names are sorted and digits come before letters.

The folder holds 2025, logs, logs-copy and notes-2026.txt, and logs keeps only this year's logs.

Check: logs-copy has four logs, logs has two, and no notes.txt is left.

A path that fails: making the copy with mv logs logs-copy. That moves the folder, so no logs folder is left, and there is no copy at all.

When you are stuck: cp or mv did something you did not expect

cp: -r not specified: the thing to copy is a folder; add -r.

A file holds the wrong text after cp or mv: it was replaced. Next time, add -i.

No such file or directory, about the target: the folder you are copying into must exist first.

Not sure of the order? The thing first, then where it goes.

Your turn

echo one > a.txt
cp a.txt b.txt
mv a.txt c.txt
ls
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b.txt  c.txt
  1. cp makes b.txt, and a.txt stays.
  2. mv renames a.txt to c.txt.
  3. So b.txt and c.txt are left.

It prints b.txt c.txt.

How do you rename draft.txt to final.txt?Tap to reveal
  1. Renaming is moving within one folder.

mv draft.txt final.txt.

Why does cp need -r for a folder, while mv does not?Tap to reveal
  1. cp must copy every file inside, all the way down.
  2. mv only gives the folder a new place in the tree.

Because cp copies everything inside, and mv only moves the folder.

Did you know?

Why a big move can be instant

A move that stays inside one file system copies nothing. The GNU manual says that mv normally renames the file, and the Linux rename call moves the name from one folder to another, so the size of the file does not matter. Across two file systems the rename fails with the error EXDEV. Then mv falls back on copying, as cp -a would, and removes the original only after the copy has worked.

Why it fits here: It answers this topic's question: mv only renames inside one file system, and copies only when it has to cross to another.

Sources: GNU Coreutils manual: mv invocation; Linux man-pages: rename(2)

A name from magnetic tape

The name tar comes from tape. The GNU tar manual says it came from the phrase Tape ARchive, though archives these days rarely sit on tapes. A tar command appeared in Seventh Edition Unix, released in January 1979. GNU tar was first written by John Gilmore, and many people have changed it since.

Why it fits here: It explains the name of this topic's tar: an archiver made for magnetic tape, in Unix since 1979.

Sources: GNU tar manual: Introduction; FreeBSD manual: tar(1); Wikipedia: tar (computing); GNU tar manual: GNU tar Authors

In one line

cp copies and mv moves, both written as the thing first, then where it goes, and mv in one folder renames. A folder needs cp -r. Both replace an existing file without asking unless you add -i. tar packs a folder into one archive.

Removing, with care

At a glance

In a desktop's file manager, a deleted file goes to a bin, and you can take it out again. The shell has no bin: what rm removes is gone for good, and no undo brings it back.

A folder needs rm -r, which takes everything inside it. The safe habit is to look first: run ls with the same names, and when the list is right, change ls to rm. The option -i asks before each removal, and -f never asks.

Take a guess: Where does the desktop's bin keep the files you delete?

In a desktop's file manager, a deleted file goes to a bin, and you can take it out again. The shell has no bin. When rm removes a file, the file is gone, and no undo brings it back. That one fact shapes every habit in this section.

rm: remove files

touch old.txt older.txt keep.txt
rm old.txt older.txt
ls
keep.txt

The name rm is short for remove, and it prints nothing when it works. A name that is not there gets a complaint and a status of 1. The other names are still removed:

touch a.txt
rm a.txt nothing.txt
echo $?
ls
rm: cannot remove 'nothing.txt': No such file or directory
1

Folders: rm -r

The command rm refuses a folder unless you add -r, which removes the folder and everything inside it. It is the most dangerous everyday command there is, so read every rm -r twice before you press Enter:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

rm logs
rm -r logs
ls
rm: cannot remove 'logs': Is a directory
notes.txt
OptionIt doesUse it
-rremoves folders and everything in themwith care, every time
-iasks before each removalwhen you are not sure
-vsays what it removedto see what happened
-fnever asks, and is quiet about missing namesin scripts, and rarely by hand

With -v, rm reports each thing as it goes. A folder can only go once it is empty, so the deepest things go first:

mkdir -p old/deep
touch old/deep/crate.txt
rm -rv old
removed 'old/deep/crate.txt'
removed directory 'old/deep'
removed directory 'old'

With -i, rm asks about each one, and only y removes it:

Typed: n, then Enter, at the question

asha@tower:~/shop$ rm -i keep.txt
rm: remove regular empty file 'keep.txt'? n
asha@tower:~/shop$ ls
keep.txt
asha@tower:~/shop$ 

Look, then act

Here is the habit that would have saved Corin's logs. Before any rm, run ls with exactly the same names, and read the list. If it is right, press the up arrow, change ls to rm, and press Enter. The names cannot change in between, because you did not type them again.

A space in the wrong place causes most disasters. Here a stray space splits one pattern into two words. The next section explains patterns, but the danger is plain: a lone * means every name in the folder.

touch a.log b.log keep.txt
rm * .log
ls
rm: cannot remove '.log': No such file or directory

The ls at the end prints nothing. The folder is empty, and keep.txt went too. The person meant *.log, the names that end in .log. On this page that costs nothing; on a server it can cost a week of work.

rm -rf

You will see rm -rf in tutorials. The f means never ask and never complain, so a mistyped path is removed in silence. Never run an rm -rf that you copied without reading every word of it. Never run one on a path that starts with /.

Worked example 4

Corin's job, done properly: remove last year's logs, the two whose names start with 2025, and keep this year's. Look first, then act, then check.

What we have: the logs folder, with two logs from 2025 and two from 2026

What we need: only the 2025 logs removed

The plan: list exactly the names you will remove; if the list is right, bring the line back and change ls to rm; then list the folder

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

ls logs/2025-01.log logs/2025-02.log
logs/2025-01.log  logs/2025-02.log
  1. The list shows the two old logs, and nothing from 2026. So the same names are safe to remove.

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

rm logs/2025-01.log logs/2025-02.log
ls logs
2026-01.log  2026-02.log
  1. The up arrow brought back the ls line, and only its first word changed.

Only 2026-01.log and 2026-02.log remain.

Check: the last ls shows this year's two logs, and no name from 2025.

A path that fails: rm logs/*, which is what Corin said. The * means every name in logs, so this year's logs went too.

When you are stuck: rm will not remove something, or removed too much

Is a directory: rm needs -r for a folder, or use rmdir if the folder is empty.

No such file or directory: check the name with ls, or let Tab write it.

You removed the wrong thing: rm has no undo. Look for a copy, such as a backup, or Git, which the next step teaches.

Not sure what a line will remove? Run it with ls in place of rm first.

Your turn

touch a b c
rm a c
ls
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
b
  1. touch makes three empty files.
  2. rm removes two of them.

It prints b.

What is the difference between rmdir and rm -r?Tap to reveal
  1. rmdir removes a folder only when it is empty.
  2. rm -r removes a folder and everything in it.

rmdir needs an empty folder; rm -r takes everything inside.

Before you type rm logs/2025-*, what should you type first, and why?Tap to reveal
  1. ls with the same names shows exactly what rm would get.

ls logs/2025-*, to see exactly what will be removed.

Did you know?

A second or two, 300 GB

Removing on the wrong machine is a classic mistake. GitLab's own report says that on 31 January 2017 an engineer meant to empty the data folder on the standby database server, a spare copy, but the command ran on the main server instead. The engineer stopped it a second or two later, yet around 300 GB was already gone. About 5000 projects, 5000 comments and 700 new user accounts were affected.

Why it fits here: It shows why this topic says look before you remove: check the names, and check which machine you are on.

Source: GitLab: Postmortem of database outage of January 31

The bin is a hidden folder

The desktop's bin is an ordinary folder. The freedesktop.org Trash Specification gives trash programs one common way to store files, and it puts each user's bin at $XDG_DATA_HOME/Trash, which is ~/.local/share/Trash unless set otherwise. A trashed file is moved into its files folder. A note ending in .trashinfo records the file's original path and the date it was trashed, and that note is how a file goes back.

Why it fits here: It answers this topic's question: the desktop's bin is a folder in your home, which the shell's rm never uses.

Sources: freedesktop.org: Trash Specification; freedesktop.org: XDG Base Directory Specification

In one line

rm removes files for good: there is no bin. A folder needs -r, which takes everything inside it. Look first with ls and the same names, then change ls to rm. The option -i asks before each removal, and -f never asks.

Patterns: one word for many names

At a glance

Typing four log names is tedious, and typing four hundred is impossible. The shell lets you describe names instead of listing them.

You write a pattern, and before the command starts, the shell swaps it for every name in the folder that fits. This swapping is called expanding the pattern. A star means any run of characters, a question mark one character, and brackets one character from a set. Braces make words whether or not files exist, and quotes turn patterns off.

Take a guess: What does a Mac's shell do with a pattern that matches no file at all?

Typing four log names is tedious, and typing four hundred is impossible. The shell lets you describe names instead of listing them. You write a pattern, and the shell swaps it for every name in the folder that fits, before the command even starts.

Glob

A pattern with wildcards such as * and ?, which the shell turns into the matching file names. Turning a pattern into names is called expanding it.

The best way to see a pattern at work is with echo, which prints the words it receives after the shell has expanded them:

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

echo logs/*.log
echo logs/2025-*
logs/2025-01.log logs/2025-02.log logs/2026-01.log logs/2026-02.log
logs/2025-01.log logs/2025-02.log

The command echo did not search for anything. The shell replaced each pattern with the matching names, in sorted order, and echo printed what it received. Every command gets the same list. So ls logs/2025-* and rm logs/2025-* name exactly the same files, which is why looking first with ls works.

WildcardMatchesExampleFits
*any run of characters, even none*.logevery name that ends in .log
?exactly one character2026-0?.log2026-01.log to 2026-09.log
[12]one of these characters2025-0[12].logJanuary and February
[0-9]one character in this rangepump[0-9]pump0 to pump9
[!a]one character that is not one of these[!.]*names that do not start with a dot

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

echo logs/202?-01.log
echo logs/2026-0[12].log
echo logs/*-02*
logs/2025-01.log logs/2026-01.log
logs/2026-01.log logs/2026-02.log
logs/2025-02.log logs/2026-02.log

Two surprises

First, * does not match a dot at the start of a name, so patterns skip hidden files, as ls does. Second, a pattern that matches nothing is left as it is, and the command then receives the pattern itself:

touch .secret shown.txt
echo *
ls *.log
shown.txt
ls: cannot access '*.log': No such file or directory

The error names *.log, star and all, because no file matched and the shell passed the pattern on unchanged. When you see a star in an error message, a pattern found nothing.

Braces make words

Braces look similar and work differently. {a,b} makes one word for each item in the list, and {1..5} makes a word for each number in the range. Braces never look at the folder, so they can make names that do not exist yet. That makes them the tool for creating things:

echo pump{1,2,3}
echo {1..5}
mkdir -p stores/{2025,2026}
ls stores
pump1 pump2 pump3
1 2 3 4 5
2025  2026

Here is a neat trick. cp notes.txt{,.bak} becomes cp notes.txt notes.txt.bak, because the list's first item is empty. One short command makes a backup copy.

Quotes stop patterns

Sometimes you want a star to be only a star. Quotes turn patterns off, and the three kinds of quoting differ in how much they protect:

WrittenProtectsSo
'*.log'single quotes: everything insideno pattern, and no $ name
"*.log"double quotes: spaces and patterns, but not $a $ name is still filled in
\*.loga backslash: the one character after itonly that star

In a folder with a.log and b.log

echo *.log
echo '*.log' "*.log" \*.log
echo "Home: $HOME"
echo 'Home: $HOME'
a.log b.log
*.log *.log *.log
Home: /home/asha
Home: $HOME

$HOME is a name that the shell fills in with your home folder, and the environment lesson explains such names. For now, remember the rule. Use double quotes for text that should keep its spaces, and single quotes for text that should stay exactly as typed.

Worked example 5

The store has twelve monthly logs for 2026. Warden Rao wants the logs for January to March listed with one short pattern. Then she wants an empty folder for each quarter of the year, q1 to q4, made with one command.

What we have: twelve logs named 2026-01.log to 2026-12.log, in a folder named logs

What we need: a pattern for three months, and four new folders

The plan: the months 01 to 03 share a 0 and end in 1, 2 or 3, so use [1-3] after the 0; braces make names, so use them for the new folders

In a folder with a logs folder of twelve monthly logs

ls logs/2026-0[1-3].log
mkdir q{1..4}
ls -d q*
logs/2026-01.log  logs/2026-02.log  logs/2026-03.log
q1  q2	q3  q4
  1. The brackets matched one character, 1, 2 or 3, in the one place where the months differ. The braces made four words before mkdir ran. The option -d lists the folders themselves, not what is inside them.

The pattern is 2026-0[1-3].log, and mkdir q{1..4} makes the folders.

Check: ls found exactly three logs, and the four folders are there.

A path that fails: ls logs/2026-0*.log. The * after the 0 matches any digit, so April to September come too: nine logs, not three.

When you are stuck: a pattern does not match what you expected

Put echo in front of the command, and read the list that the pattern makes.

A star in an error message: the pattern matched nothing, so check the folder with ls.

A hidden file is missing: * skips names that start with a dot, so start the pattern with a dot, as in .s*.

Braces did nothing: there must be no space inside them, and a comma or two dots between the items.

Your turn

touch a1 a2 b1
echo a*
echo ?1
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a1 a2
a1 b1
  1. a* matches the names that start with a.
  2. ?1 matches any one character, then a 1.

It prints a1 a2, then a1 b1.

Which pattern matches 2026-01.log and 2026-02.log, but not 2026-03.log?Tap to reveal
  1. Only the last digit of the month differs.
  2. Brackets give a choice of one character.

2026-0[12].log.

What does echo '$HOME' print, and why?Tap to reveal
  1. Single quotes keep everything inside exactly as typed.

$HOME, as single quotes stop the shell filling it in.

Did you know?

Glob was once a program

Pattern matching was once a separate program. The Linux manual for glob says that long ago, in Unix V6, a program called /etc/glob expanded wildcard patterns. Soon afterwards the job became part of the shell itself. Today there is also a library routine, glob, that does the same work for any program, and the old name is still the word for patterns like these.

Why it fits here: It shows where this topic's patterns came from: a separate program in Unix V6, later built into the shell.

Source: Linux man-pages: glob(7)

On a Mac, no match is an error

Not every shell passes on a pattern that matches nothing. Apple says that starting with macOS 10.15, a Mac uses zsh as its default shell. The zsh manual says its NOMATCH option, on by default in zsh, prints an error when a pattern has no matches, instead of leaving the pattern unchanged. So ls *.log in a folder with no logs gets an error from zsh, where bash would hand the star to ls.

Why it fits here: It shows that this topic's rule for a pattern that matches nothing is bash's rule: zsh, the Mac's shell, gives an error instead.

Sources: Apple Support: Use zsh as the default shell on Mac; zsh manual source: options

In one line

The shell expands a pattern into the matching names before the command runs: * is any run of characters, ? one character, and brackets one of a set. Braces make words whether or not files exist. Quotes turn patterns off.

Finding files

At a glance

A pattern only looks in one folder. When you do not know where a file is, you need a search that walks down through every folder below a starting point.

That search is find. A find command has three parts: where to start, what to test, and what to do with each match. The tests include -name with a quoted pattern, -type, -size and -mtime, and all of them must be true. With no action, find prints each path; -exec runs a command on each match, and -delete removes it.

Take a guess: Does the place of -delete in a find command matter?

A pattern only looks in one folder. When you do not know where a file is, you need a search that walks down through every folder below a starting point. That is find. You met it in the last lesson; here it learns its most useful tests.

A find command has three parts: where to start, what to test, and, if you like, what to do with each match. With no action, it prints the path of each match. One detail first: find lists names in the order the disk happens to keep them, which is not sorted, and which can differ from one machine to the next. So the blocks here add | sort, which puts the lines in order; the next lesson explains the | sign.

In the same folder, with a pumps folder too: north holds gauge.txt and a long readings.log, and south a short readings.log

find . -name '*.log' | sort
./logs/2025-01.log
./logs/2025-02.log
./logs/2026-01.log
./logs/2026-02.log
./pumps/north/readings.log
./pumps/south/readings.log

Notice the quotes round the pattern. find must receive *.log itself, so that it can test every name it meets. Without the quotes, the shell would expand the pattern first, in the starting folder, and hand find whatever names happened to match there. The mistakes section shows what that does.

The tests you will use most

TestFindsExample
-name 'p'names that fit the pattern-name '*.log'
-iname 'p'the same, ignoring capitals-iname 'readme*'
-type ffiles only; -type d finds folders-type d
-size +1kbigger than 1 KiB, folders too; - means smaller-size +10M
-mtime -7changed less than 7 days ago; + means more-mtime +30
-maxdepth 1only this many levels down-maxdepth 2

Tests written one after another must all be true, so each one narrows the search:

In the same folder, with a pumps folder too: north holds gauge.txt and a long readings.log, and south a short readings.log

find . -type d | sort
find . -name 'readings*' -type f | sort
find . -type f -size +1k
find . -maxdepth 1 -type f
.
./logs
./pumps
./pumps/north
./pumps/south
./pumps/north/readings.log
./pumps/south/readings.log
./pumps/north/readings.log
./notes.txt

The dot in the first answer is the starting folder itself, which is a folder too. Only one file is bigger than 1 KiB, the long readings log. The -type f matters there: a folder's own list of names counts as 4 KiB on many disks, as ls -l showed in the last lesson, so without it every folder would be found too. And -maxdepth 1 kept find in the starting folder, where notes.txt is the only file.

Age works the same way. This block dates the two 2025 logs back to the year 2020 with touch -d, which sets a file's date, then searches by age:

In the same folder, with a pumps folder too: north holds gauge.txt and a long readings.log, and south a short readings.log

touch -d 2020-01-01 logs/2025-01.log logs/2025-02.log
find logs -mtime +30 | sort
find logs -type f -mtime -1 | sort
logs/2025-01.log
logs/2025-02.log
logs/2026-01.log
logs/2026-02.log

Doing something with each match

The action -exec runs a command for each match. The pair {} stands for the path that was found, and the line ends with \;, a semicolon with a backslash so that the shell passes it to find:

In the same folder, with a pumps folder too: north holds gauge.txt and a long readings.log, and south a short readings.log

find . -name gauge.txt -exec cat {} \;
pressure 12

The action -delete removes each match, with no bin, like rm. Always run the same find without -delete first and read the list. Then put -delete at the very end. The manual of find warns that -delete placed first makes find try to delete everything below the starting folder.

In a folder with keep.txt, a.tmp, and a logs folder holding b.tmp

find . -name '*.tmp' | sort
find . -name '*.tmp' -delete
find . -type f
./a.tmp
./logs/b.tmp
./keep.txt

Worked example 6

Somewhere below this folder are logs of every kind. Warden Rao wants to know how many .log files there are in all, and which file of any kind is bigger than 1 KiB.

What we have: a tree of folders, with logs in more than one place

What we need: a count of .log files, and the path of any file over 1 KiB

The plan: find with -name counts the logs once wc -l counts its lines; find with -size +1k and -type f finds the big file

In the same folder, with a pumps folder too: north holds gauge.txt and a long readings.log, and south a short readings.log

find . -name '*.log' | wc -l
find . -type f -size +1k
6
./pumps/north/readings.log
  1. Each match is one line, so counting the lines counts the files. The | sends find's list to wc.

There are 6 logs, and ./pumps/north/readings.log is the big file.

Check: the sorted list earlier in this section shows the same six logs.

A path that fails: ls *.log. That looks only in the starting folder, which holds no .log file, so ls reports the pattern itself as missing.

When you are stuck: find does not find what you expected

Quote the pattern: -name '*.log', never -name *.log.

Check the starting folder: find only looks below it.

Tests written together must all be true. Remove one at a time to see which one rules a file out.

The order changes between machines: add | sort when the order matters.

Your turn

find . -type d | sort
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
.
./pumps
./pumps/north
  1. -type d keeps only folders.
  2. The starting folder, ., is a folder too.

It prints ., ./pumps and ./pumps/north.

Write a find that lists every folder below the current one, and nothing else.Tap to reveal
  1. Start at the dot.
  2. -type d keeps folders.

find . -type d.

You want to remove every .tmp file below the current folder. What do you run first, and what second?Tap to reveal
  1. Look first: the same find, with no action.
  2. Then add -delete at the end.

First find . -name '*.tmp', then find . -name '*.tmp' -delete.

Did you know?

Order matters for -delete

In a find command, the order of the parts matters. The find manual warns that find reads its command line as an expression, so putting -delete first makes find try to delete everything below the starting points. Two parts in a row are joined by and, and the second is not tried when the first is false. Written last, -delete removes only what the tests before it have matched.

Why it fits here: It answers this topic's question: -delete written first removes everything below the start, and written last only the matches.

Source: Linux man-pages: find(1)

Ages counted in whole days

find's test of age rounds down. The find manual says -mtime counts in periods of 24 hours, and any fractional part is ignored. So -mtime +1 does not mean more than one day old: a file must be at least two days old to match. A file changed 47 hours ago counts as one whole day, and one is not more than one.

Why it fits here: It sharpens this topic's -mtime test: a file's age is counted in whole periods of 24 hours, rounded down.

Source: Linux man-pages: find(1)

In one line

find walks every folder below a starting point and tests each name: -name with a quoted pattern, -type, -size, -mtime and more, all of which must be true. It can act on each match with -exec or -delete; look before you delete.

Where it is used

These commands are the daily bread of anyone who works on a server or builds software. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
mkdir -psetting up a projecta site's css, js and img folders
head, tailreading logsthe last lines of a server's error log
tail -fwatching a running programrequests arriving at a web server
cp -ra copy before a risky changea site's files before an update
mvrenaming and tidyingphotos sorted into folders
look, then rmclearing out old fileslast year's logs on a full disk
patternsevery file of one kind*.jpg in a downloads folder
finda lost file, or every big onewhat is filling up the disk
tar -czfone file for a whole foldera backup, or a download that ends in .tar.gz

Mistakes and debugging

These are the slips that people meet most often with files. Every output below is the real one, from the code shown.

1. A folder given to cp without -r

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cp logs backup
cp: -r not specified; omitting directory 'logs'

No copy was made. The fix: cp -r logs backup.

2. rmdir on a full folder

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

rmdir logs
rmdir: failed to remove 'logs': Directory not empty

This is rmdir keeping you safe. The fix: look inside with ls, and remove the folder with rm -r only if you mean everything in it.

3. Copying into a folder that is not there

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

cp notes.txt backup/
cp: cannot create regular file 'backup/': Not a directory

The slash at the end says backup is a folder, and there is no such folder. The fix: mkdir backup first.

4. Moving several files to a missing folder

touch a.txt b.txt
mv a.txt b.txt store
mv: target 'store': No such file or directory

With more than one file, the last name must be a folder that exists. The fix: mkdir store, then the mv.

5. A pattern that matches nothing

In a folder with notes.txt, and a logs folder of four monthly logs, two from 2025 and two from 2026

ls logs/*.txt
ls: cannot access 'logs/*.txt': No such file or directory

The star in the message means that no name matched, so the pattern itself was passed on. The fix: ls logs to see the real names.

6. A pattern given to find without quotes

touch a.log b.log
find . -name *.log
find: paths must precede expression: `b.log'
find: possible unquoted pattern after predicate `-name'?

The shell expanded *.log into a.log b.log before find ran, so find received one name too many, and even guesses why. The fix: find . -name '*.log'.

The debugging corner: put echo in front

Not sure what a line will do? Write echo before it. echo rm logs/2025-* prints the exact command that would run, with every pattern already expanded, and removes nothing. When the printed line is right, remove the echo.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

mkdir -p stores/2026            # a chain of folders
touch stores/index.txt          # an empty file
cp -r logs stores/logs          # copy a folder
mv notes.txt stores             # move a file into a folder
ls stores
head -n 1 stores/logs/2026-01.log
echo rm stores/logs/2025-*      # see what rm would get
rm stores/logs/2025-*           # then remove
ls stores/logs
find . -name '*.log' | sort     # every log, anywhere below
2026  index.txt  logs  notes.txt
pump one ok
rm stores/logs/2025-01.log stores/logs/2025-02.log
2026-01.log  2026-02.log
./logs/2025-01.log
./logs/2025-02.log
./logs/2026-01.log
./logs/2026-02.log
./stores/logs/2026-01.log
./stores/logs/2026-02.log
When you seeIt meansLook at
-r not specified; omitting directorycp was given a foldercp -r
Is a directory, from rmrm was given a folderrm -r, or rmdir if it is empty
Directory not emptyrmdir removes empty folders onlyls inside it first
File existsthe name is takenanother name, or mkdir -p
a star in an errora pattern matched nothingls, or echo the pattern
paths must precede expressionan unquoted pattern in findquotes round the pattern
overwrite 'a.txt'?-i is askingy to replace, n to keep
target 'store': No such file or directorythe target folder is missingmkdir it first

The story: Look, then act

You sort the stores properly: a folder for each year, every crate under its true name, a copy made before anything is moved. Before each removal you ask the tube to list what a pattern matches, and only when the list is right do you say the word that removes. The patterns save you a hundred lines of speaking.

By evening the wall is in order, and a second copy of everything sits in the far store.

Corin reads the list twice before he speaks now. Warden Rao notices, and says nothing, which is the most she ever says.

Reagents gathered: mkdir, cp, mv, rm, glob, quoting.

Sources

  • GNU Bash Reference Manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)
  • GNU Coreutils manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)