Basic

Creating and moving files

The commands that change a filesystem are the ones you should be most careful with, and the ones most worth automating. cp copies, mv moves, mkdir makes folders, and rm removes. Only one of those four is destructive, and knowing which one is the whole point.

What you will see

Only keep.md remains - the .md file was never in the glob.

About 2 min of reading

Try It

Preview before removing.

1

Create throwaway files

mkdir -p tmpdemo && touch tmpdemo/one.txt tmpdemo/two.txt tmpdemo/keep.md

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Three files in tmpdemo.
2

Preview the glob

ls tmpdemo/*.txt

Before you run it, say out loud what it will print. Then open the answer.

What it prints
two of the three files. That preview is the check that makes rm safe enough to run.
3

Remove only those

rm tmpdemo/*.txt && ls tmpdemo

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Only keep.md remains - the .md file was never in the glob.

Data Flow

A name is checked, then acted on.
1 List what the glob matches
↓
2 Confirm the list is what you meant
↓
3 Run the command on that list
↓
4 List again to see the result
Why this works
Quote every name

Unquoted names break on spaces and on characters like * and ?. Quoting is one keystroke that removes a whole class of failure, and it is the reason scripts that skip quoting are quietly wrong on half the files they touch.

Prefer explicit over clever

A command that names the files it touches can be reviewed. A command with a wildcard has to be reasoned about, and reasoning about a glob under time pressure is where the wrong files get removed.

Examples

mkdir before you write

mkdir -p out/ then write into out/. Writing to a folder that does not exist fails with a message that names the folder, which is a good failure. Creating first makes the intent visible in the command history.

mv overwrites silently

mv a b replaces b with no warning. If b was the file you meant to keep, it is gone. Use mv -i for an interactive prompt in a terminal, and check the target exists before an overwrite in a script.

rm -rf is not a joke

Recursive removal has no undo. The protection is not a flag, it is running ls on the same glob first and confirming the list. Make that habit before you ever type rm with a wildcard.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Moving around a filesystem
Previous Lesson
Moving around a filesystem
Next Lesson
Reading files from the terminal
Reading files from the terminal →