Reading and changing files
In the terminal, you choose exactly how to read a file: all at once, one screen at a time or just a few lines. You will also create, edit, copy, move and delete files, then connect commands so they run only when they should.
Reading a whole file
On a desktop you open a file by double-clicking it, and an app decides how to show it. In the terminal you choose the program yourself. The simplest one is cat, which prints a file's contents straight into the terminal:
$ cat shopping.txt
bread
apples
coffeeThe name comes from "concatenate": given several files, cat prints them one after another, as if they were joined into one. That makes it ideal for short files. For a file with hundreds of lines, the start scrolls off the top of the window before you can read it.
For longer files, use less. It opens the file one screen at a time and lets you move around in it without changing anything:
| Key | What it does in less |
|---|---|
| Space or b | Forward or back one screen |
| Down or Up | Forward or back one line |
| g or G | The first or the last line |
| / then a word, then Enter | Search forward for that word; n jumps to the next match |
| q | Quit and return to the prompt |
q is also how you left a manual page, because man shows its pages through less, so all of these keys work there too. Running less -N notes.txt adds a line number in front of every line, which helps when someone asks you to look at "line 212".
Reading part of a file
Often you only need one end of a file. head prints the first lines and tail prints the last ones, ten by default. The -n option chooses how many:
head -n 3 app.log
tail -n 5 app.logCounting works the same way in both: the first line of a file is line 1. So if you want line 40, head -n 40 prints lines 1 to 40, and line 40 is the last one it shows. The next lesson, Connecting commands with pipes and redirection, shows how to hand that output to tail -n 1 so that only line 40 appears.
tail has one more trick that makes it a favorite for log files. With -f, for "follow", it prints the last lines and then keeps waiting, printing each new line as a program adds it. Press Ctrl+C to stop watching.
Before you open a file, it helps to know how big it is. wc, short for "word count", prints the number of lines, words and bytes, followed by the name. A byte is the unit a file's size is measured in; in plain English text, each character takes one byte, and so does the end of each line.
$ wc shopping.txt
3 3 20 shopping.txt
$ wc -l shopping.txt
3 shopping.txt-l asks for lines only, and -w and -c ask for words or bytes. On macOS, wc pads each number with extra spaces on the left. The numbers mean the same thing; only the spacing differs.
Creating and editing files
You met touch in Finding your way around files and directories. It creates an empty file, which is useful when a program expects a file to exist. To put words in a file, you need an editor. nano is a small one that runs inside the terminal and lists its main shortcuts along the bottom of the screen:
nano shopping.txtIf the file does not exist yet, nano starts with an empty page and creates the file when you save. Type as you would in any text box, and use the arrow keys to move. In the shortcut list, ^ means the Ctrl key:
- Ctrl+O writes the file out, which means saving it. nano asks for the file name; press Enter to keep it.
- Ctrl+X exits. If there are unsaved changes, nano asks whether to save them first: press Y or N.
Ubuntu 24.04 (Windows with WSL, or Linux)
Ubuntu includes GNU nano. The top line shows its version and the file name.
macOS 14 or later with Homebrew
On macOS, the nano command opens a close relative called pico, and its top line says UW PICO. The shortcuts above work the same way.
Text editors are a matter of taste, and you may later prefer a larger one. For this course, nano is enough.
Copying, moving and deleting
cp copies a file. The first argument is the file you have and the second is where the copy goes:
cp shopping.txt shopping-backup.txtmv moves a file. Moving it into another directory and renaming it are the same operation, because a file's name is part of its path. There is no separate rename command:
mv shopping.txt groceries.txt
mkdir -p lists
mv groceries.txt lists/Both commands share a habit worth knowing early: if the destination already exists, they replace it without asking. Copying a draft over yesterday's finished version leaves you with two copies of the draft. Add -i, for "interactive", and they ask before replacing anything. To copy a whole directory with everything inside it, cp needs -r, for "recursive": cp -r lists lists-backup.
rm removes files. It is the command to treat with the most respect, because it has no undo. Nothing goes to a Trash or Recycle Bin, and there is no command that brings the file back. A few habits keep it safe:
- Run
lswith the same names first, so you see exactly whatrmwould remove. That matters most with a wildcard:ls *.txtshows whatrm *.txtwould take. - Use
rm -iwhen you are unsure. It asks about each file before removing it. rmrefuses to remove a directory unless you add-r. Read the path one more time before you do: with-r, it removes the directory and everything below it.
cp shopping.txt shopping-backup.txt
- shopping.txt
- Unchanged
- Second name
- shopping-backup.txt, a copy
- Way back
- Remove the copy
Two files
mv shopping.txt groceries.txt
- shopping.txt
- Gone
- Second name
- groceries.txt, the same file
- Way back
- mv it back
One file
rm shopping.txt
- shopping.txt
- Gone
- Second name
- None
- Way back
- None: no Trash, no undo
No file
If the destination already exists, cp and mv replace it without asking. -i makes them ask first.
Names, extensions and contents
A file has a name and some contents, and the two are more separate than they look. You already know one naming rule: a name that starts with a dot is hidden, so ls skips it unless you add -a. Programs keep their settings in hidden files, called dotfiles, so they stay out of the way. bash, for example, reads ~/.bashrc each time it starts. Hidden files are otherwise ordinary: cat, cp and rm treat them like any other file.
The part of a name after the last dot, such as .txt, .png or .json, is the extension. A desktop uses it to pick which app opens the file, but it is only part of the name. Renaming photo.png to photo.txt changes nothing inside the file. It is still an image, now with a misleading name.
To find out what a file really contains, ask file. It looks at the contents, not the name:
$ file notes.txt logo.png random.bin
notes.txt: ASCII text
logo.png: PNG image data, 64 x 64, 8-bit/color RGBA, non-interlaced
random.bin: dataEvery file is stored as a sequence of bytes, each a small number from 0 to 255. Those answers sort files into two broad kinds. A text file holds bytes that stand for readable characters, arranged in lines, by an agreed table. ASCII is the oldest such table, covering English letters, digits and punctuation, and file reports ASCII text when every byte comes from it. Text is what cat, less, head and wc -l expect. A binary file, such as an image, an archive or a program, holds bytes that only make sense to the program that reads them. file calls bytes it cannot recognize simply data.
Printing a binary file with cat fills the screen with odd symbols, and some byte sequences can confuse the terminal itself, so the prompt looks garbled afterwards. Nothing is damaged. Type reset and press Enter, even if you cannot see what you type, and the terminal returns to normal.
Joining commands
Every command finishes with an exit status, 0 for success and another number for failure, as Terminals and shells showed. Three ways of joining commands on one line decide whether the second one runs at all:
| You write | The second command runs |
|---|---|
cd lists ; ls | Always, whatever happened to the first |
cd lists && ls | Only if the first succeeded, with status 0 |
cd lists || echo "No lists directory here" | Only if the first failed |
The difference shows when lists does not exist. With ;, cd fails and ls runs anyway, listing the directory you never left, which is easy to mistake for the one you wanted. With &&, ls is skipped. With ||, the message runs only because cd failed. && is the safe choice whenever a command depends on the one before it, such as ls old-notes.txt && rm -i old-notes.txt, which offers to remove the file only after showing that it exists.
A file of commands
When you find yourself pasting the same few lines again and again, you can keep them in a file. Open a new file in nano, type the commands one per line, and save it. A file of commands is the simplest kind of script:
# steps.sh: how long the list is, and how it starts
wc -l groceries.txt
head -n 2 groceries.txtThen hand the file to bash:
bash steps.shbash reads the file and runs its lines in order, just as it runs a pasted block: the comment is skipped, and each line runs whether or not the one before it worked, unless you joined them with &&. The .sh extension is only part of the name. It tells people the file holds shell commands, and bash would run it under any name. To change what the file does, edit it in nano and run it again; the work is repeated exactly, with only the change you made.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Read, copy, rename and remove files, then find two words in a long oneWrite a file with nano, read a long file with less, head and tail, copy, move and remove files safely, join commands, and find your two words with a file of commands.