18  18. Writing to Files: echo, >, >>, and cat

This page shows how to put text into a file straight from the command line, how to look at what’s inside a file, and why quotes matter when you type text in Bash. You will use these skills all the time, for example to add a setting to a configuration file.

18.1 Printing text with echo

The echo command prints whatever you give it:

echo "message goes here"

Output:

message goes here

On its own that isn’t very exciting. echo becomes useful when you combine it with redirection.

18.2 Saving output to a file with >

Normally a command’s output (the text it prints) appears on the screen. The > symbol redirects the output into a file instead:

echo "message goes here" > message.txt

Nothing appears on the screen, because the text went into message.txt. The cat command displays a file’s contents:

cat message.txt

Output:

message goes here

Here is how > works:

  • If the file doesn’t exist, > creates it.
  • If the file already exists, > replaces (overwrites) its old contents, without any warning.

Let’s watch this happen with the practice files from Files, Folders, and Paths. The file ideas.txt starts out empty.

cd ~/Documents/bash-tutorial-files/documents/notes
echo "Idea 1: a budget tracker app" > ideas.txt
cat ideas.txt

Output:

Idea 1: a budget tracker app

Now write a second idea, again with >:

echo "Idea 2: a club sign-up site" > ideas.txt
cat ideas.txt

Output:

Idea 2: a club sign-up site

Idea 1 is gone. > threw away the old contents and wrote only the new line.

> overwrites without asking

There is no undo and no Trash. echo "oops" > report.txt silently destroys whatever was in report.txt. Double-check the file name before you press Enter.

18.3 Adding to a file with >>

Two arrows, >>, append: they add the new text to the end of the file and keep what is already there. (If the file doesn’t exist yet, >> creates it, just like >.)

echo "Idea 1: a budget tracker app" > ideas.txt
echo "Idea 2: a club sign-up site" >> ideas.txt
echo "Idea 3: a study-group finder" >> ideas.txt
cat ideas.txt

Output:

Idea 1: a budget tracker app
Idea 2: a club sign-up site
Idea 3: a study-group finder

The first line uses > to start the file fresh; the next two use >> to add lines to it.

> (one arrow) >> (two arrows)
File doesn’t exist yet creates it creates it
File already exists replaces everything in it adds to the end
Memory aid “write over” “add more”

Redirection works with any command that prints something, not just echo. For example, ls > file-list.txt saves the list of files in the current folder, and date >> log.txt adds the current date and time to the end of a log file.

18.4 Looking inside files: cat, less, head, and tail

Command What it does
cat ideas.txt Prints the whole file. Best for short files. cat a.txt b.txt prints both files, one after the other (“cat” is short for concatenate, meaning “join together”).
less ideas.txt Shows a long file one screen at a time. Space = next page, b = back, /word = search for “word”, q = quit.
head ideas.txt Prints the first 10 lines. head -n 2 ideas.txt prints the first 2.
tail ideas.txt Prints the last 10 lines. tail -n 1 ideas.txt prints the last 1.
head -n 2 ideas.txt

Output:

Idea 1: a budget tracker app
Idea 2: a club sign-up site
tail -n 1 ideas.txt

Output:

Idea 3: a study-group finder

head and tail shine with big files. For a data file with a million rows, head -n 5 sales.csv shows the column headings and the first few rows without flooding your screen.

Stuck inside less?

If the screen is full of text and your prompt doesn’t come back, you are probably inside less (or a similar viewer, such as a man page). Press q.

18.5 Quotes keep text together

Before running a command, Bash splits the line you typed into words wherever there are spaces. Extra spaces between words are simply thrown away. Quotes keep the text inside them together as one piece, spaces and all:

echo Hello     World
echo "Hello     World"
echo 'Hello     World'

Output:

Hello World
Hello     World
Hello     World

Quotes also protect characters that have a special meaning to the shell. Without quotes, the shell acts on those characters before echo even runs. Try this in the notes folder:

echo 5 * 3 = 15
echo "5 * 3 = 15"

Output:

5 ideas.txt meeting-notes.txt 3 = 15
5 * 3 = 15

The unquoted * was replaced by the names of the files in the folder. (* is a wildcard; see Wildcards and Pipes.) Here is another surprise:

echo Sales > Costs

This prints nothing. Bash saw the > and created a file named Costs that contains the word Sales. With quotes, echo "Sales > Costs" prints Sales > Costs as intended.

Characters that need this kind of protection include the space, >, <, |, ;, &, *, ?, #, $, and !. Putting your text in quotes is the simplest fix. The same goes for file names that contain spaces: echo "hello" > "my notes.txt".

You may have noticed that “double quotes” and ‘single quotes’ both kept the spaces. They are not the same, though. There is an important difference, which involves the $ character. It is explained in Single Quotes vs. Double Quotes, right after you learn about environment variables.

Rule of thumb for now

Use either kind of quotes for ordinary text. If your text contains $ or !, use single quotes: echo 'Total: $5. Great job!'

On a Mac, echo "Great job!" (with double quotes) leaves you at a strange dquote> prompt. Press Ctrl+C to get your normal prompt back, then use single quotes.

18.6 Text files and binary files

Everything we created on this page is a text file: a file that contains only characters (letters, digits, punctuation, spaces, and line breaks). Code, web pages, data files, and settings files are all text files, for example .txt, .csv, .py, .html, .css, .md, .json, and .sh files.

A binary file stores data in a format meant for a program, not for people: images (.jpg, .png), audio (.mp3), PDFs, and Office documents such as .docx and .xlsx. If you cat a binary file you get a screen full of gibberish (it doesn’t damage the file).

This difference decides which program you should use to edit a file:

  • A text editor saves exactly the characters you type and nothing else. Examples: nano (runs inside the terminal, on Mac and in Git Bash), VS Code (a free, popular code editor; optional for this course), and Notepad on Windows.
  • A word processor such as Microsoft Word or Pages adds fonts, layout, and other hidden information, and saves in its own format. Never use one to write code or settings files. Word processors also like to turn straight quotes (") into “smart” curly quotes, which Bash does not recognize as quotes. The Mac’s TextEdit works like a word processor until you choose Format → Make Plain Text.

To edit a file in the terminal, type nano ideas.txt, make your changes, press Ctrl+O and then Enter to save, and press Ctrl+X to exit.

Typing a separate echo ... >> for every line gets tedious. A heredoc (“here document”) writes many lines with one command:

cat << 'EOF' > shopping.txt
eggs
milk
bread
EOF
  • Everything between the first line and the line containing only EOF goes into shopping.txt.
  • EOF (“end of file”) is just a marker. Any word works, as long as the last line matches it exactly, with nothing else on that line.
  • Putting quotes around the first marker ('EOF') tells Bash to copy the lines exactly as written, even if they contain $.
  • While you type the lines, the prompt changes (to > in Bash, or heredoc> in zsh on a Mac) until you type the final EOF.

You will see heredocs in tutorials and in commands written by AI tools, because they create a whole file in a single step.

Programs have two separate output channels: standard output for normal results and standard error for error messages. > and >> redirect only standard output, so error messages still appear on the screen:

ls no-such-folder > result.txt

The error message (“No such file or directory”) shows up on the screen, and result.txt is empty. To save error messages in a file, use 2>, for example ls no-such-folder 2> errors.txt.

Practice Questions

Easy

Question 1 · Short answer

What does the command echo "message goes here" do?

It prints the text message goes here on the screen. echo simply prints whatever you give it.

Question 2 · Multiple choice

What does echo "hi" > notes.txt do?

  1. Prints hi notes.txt on the screen
  2. Adds the line hi to the end of notes.txt, keeping the old contents
  3. Writes hi into notes.txt, replacing anything that was in it (and creating the file if needed)
  4. Checks whether hi is greater than notes.txt

c. A single > redirects the output into the file and overwrites its old contents. Option b describes >>. Option a is wrong because the output goes into the file, not to the screen. In Bash, > is not a “greater than” comparison here (d).

Question 3 · True or false

>> erases a file’s old contents before writing the new text.

False. >> appends: it keeps the old contents and adds the new text at the end. It is the single > that erases (overwrites) the old contents.

Question 4 · Matching

Match each command with what it does.

Command What it does
1. cat report.txt A. shows the last 10 lines
2. less report.txt B. prints the whole file at once
3. head report.txt C. shows the file one screen at a time
4. tail report.txt D. shows the first 10 lines

1 → B, 2 → C, 3 → D, 4 → A.

Question 5 · Short answer

You opened a long file with less and now the file fills your screen. How do you get back to your prompt?

Press q (for “quit”).

Question 6 · Multiple choice

Which of these is a text file?

  1. vacation.jpg
  2. budget.xlsx
  3. sales.csv
  4. song1.mp3

c. A .csv file contains only plain characters (values separated by commas), so you can read it with cat or edit it in a text editor. Images (.jpg), Excel workbooks (.xlsx), and audio files (.mp3) are binary files.

Medium

Question 7 · Predict the output

What does the last command print?

echo "red" > colors.txt
echo "green" >> colors.txt
echo "blue" > colors.txt
echo "yellow" >> colors.txt
cat colors.txt
blue
yellow

The third command uses >, which wipes out red and green and starts the file over with blue. Then >> adds yellow to the end.

Question 8 · Write the command

Write commands that create a file todo.txt whose first line is Email professor, then add a second line Submit assignment, and finally display the file.

echo "Email professor" > todo.txt
echo "Submit assignment" >> todo.txt
cat todo.txt

Use > for the first line (it creates the file, or starts it over) and >> for every line after that.

Question 9 · Write the command

sales.csv has 50,000 rows. Write a command that shows only its first 3 lines, and another that shows only its last 5 lines.

head -n 3 sales.csv
tail -n 5 sales.csv

Question 10 · Predict the output

What do these two commands print?

echo Total:     500     dollars
echo "Total:     500     dollars"
Total: 500 dollars
Total:     500     dollars

Without quotes, Bash splits the line into separate words and echo prints them with single spaces in between. Inside quotes, the text stays together exactly as typed, including the extra spaces.

Question 11 · Short answer

Sam typed echo Profit > Loss and nothing was printed. What happened? How should he have typed it to print the text Profit > Loss?

Bash treated > as redirection, so it created (or overwrote!) a file named Loss containing the word Profit. To print the text, put it in quotes: echo "Profit > Loss" (single quotes work too). He may also want to delete the accidental file with rm Loss.

Question 12 · Fill in the blank

To add the line Backup finished to the end of log.txt without erasing what is already there, type: echo "Backup finished" ___ log.txt

>>, giving echo "Backup finished" >> log.txt.

Question 13 · Scenario

On her Mac, Maria typed echo "Great job!" and pressed Enter. Instead of printing anything, the terminal now shows dquote>. What should she do right now, and how should she type the command instead?

Press Ctrl+C to cancel and get the normal prompt back. Then use single quotes, which protect special characters such as !: echo 'Great job!'. (The page on Single Quotes vs. Double Quotes explains what ! means to the shell.)

Hard

Question 14 · Scenario

Maria wanted to add one line to her shell settings file, but she typed:

echo 'export EDITOR=nano' > ~/.zshrc

What happened to ~/.zshrc? What should she have typed, and can she undo the mistake with a command?

The single > replaced the entire file: ~/.zshrc now contains only export EDITOR=nano, and all of its earlier settings are gone. She should have used >> to append:

echo 'export EDITOR=nano' >> ~/.zshrc

There is no undo command and no Trash for this. She can only restore the file from a backup (such as Time Machine) or retype the lost lines. This is why it’s smart to make a copy before changing an important file (cp ~/.zshrc ~/.zshrc-backup).

Question 15 · Predict the output

In a folder containing only ideas.txt and meeting-notes.txt, Maria runs:

ls > file-list.txt
cat file-list.txt

The output lists three files, including file-list.txt itself. Why?

file-list.txt
ideas.txt
meeting-notes.txt

The shell sets up the redirection before it runs the command: it creates the empty file file-list.txt first and then starts ls. By the time ls looks at the folder, the new file is already there, so it lists it too.

Question 16 · Find the bug

Sam wanted to create a file named report 2026.txt and typed:

echo "Quarterly results" > report 2026.txt

What actually happened, and how should he fix the command?

Because of the space, Bash used only report as the file name. The leftover word 2026.txt became extra text for echo, so he created a file named report containing Quarterly results 2026.txt. Fix it by quoting the file name: echo "Quarterly results" > "report 2026.txt", or better, avoid spaces in file names: report-2026.txt.

Question 17 · Long answer

A classmate writes a Python program in Microsoft Word, saves it as analysis.py, and is confused when Python reports errors. Explain what went wrong and what they should use instead.

Word is a word processor: it saves fonts, layout, and other hidden information in its own format, so the saved file is not plain text, even if it’s named .py. Word may also change straight quotes into curly “smart” quotes, which are not valid in Python code. Programs must be stored as plain text files, written with a text editor such as VS Code, nano, or Notepad, which saves exactly the characters you type and nothing else.

Question 18 · Scenario

You want to keep a record of every time you run a backup. After each backup you plan to run either date > backup-log.txt or date >> backup-log.txt. Which one should you use, and why?

date >> backup-log.txt. Each run adds a new line with the current date and time to the end of the log, so the file builds up a history. With >, every run would replace the file, so you would only ever see the most recent backup.

Question 19 · Short answer

What does this command do? (Hint: see the heredoc deeper dive.)

cat << 'EOF' > team.txt
Maria
Sam
EOF

It creates (or overwrites) the file team.txt with two lines, Maria and Sam. Everything between the first line and the closing EOF line is written into the file. Because of the >, any old contents of team.txt are replaced.

Question 20 · Hands-on

In the practice folder documents/notes, create meeting-notes.txt with these four lines, using > once and >> three times:

Meeting: project kickoff
Attendees: Maria, Sam
Decision: build a club sign-up site
Next meeting: Friday

Then (1) display the whole file, (2) display only the first line, (3) display only the last two lines, and (4) open it with less and quit.

cd ~/Documents/bash-tutorial-files/documents/notes
echo "Meeting: project kickoff" > meeting-notes.txt
echo "Attendees: Maria, Sam" >> meeting-notes.txt
echo "Decision: build a club sign-up site" >> meeting-notes.txt
echo "Next meeting: Friday" >> meeting-notes.txt
cat meeting-notes.txt
head -n 1 meeting-notes.txt
tail -n 2 meeting-notes.txt
less meeting-notes.txt

Press q to leave less. If a line comes out wrong, start over with > on the first line, or fix the file in nano.

© 2025-2026 Y. Rosenthal. All rights reserved.