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.txtNothing appears on the screen, because the text went into message.txt. The cat command displays a file’s contents:
cat message.txtOutput:
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.txtOutput:
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.txtOutput:
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.txtOutput:
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.txtOutput:
Idea 1: a budget tracker app
Idea 2: a club sign-up site
tail -n 1 ideas.txtOutput:
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.
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 > CostsThis 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.
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
EOFgoes intoshopping.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, orheredoc>in zsh on a Mac) until you type the finalEOF.
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.txtThe 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?
Question 2 · Multiple choice
What does echo "hi" > notes.txt do?
- Prints
hi notes.txton the screen - Adds the line
hito the end ofnotes.txt, keeping the old contents - Writes
hiintonotes.txt, replacing anything that was in it (and creating the file if needed) - Checks whether
hiis greater thannotes.txt
Question 3 · True or false
>> erases a file’s old contents before writing the new text.
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 |
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?
Question 6 · Multiple choice
Which of these is a text file?
vacation.jpgbudget.xlsxsales.csvsong1.mp3
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.txtQuestion 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.
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.
Question 10 · Predict the output
What do these two commands print?
echo Total: 500 dollars
echo "Total: 500 dollars"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?
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
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?
Hard
Question 14 · Scenario
Maria wanted to add one line to her shell settings file, but she typed:
echo 'export EDITOR=nano' > ~/.zshrcWhat happened to ~/.zshrc? What should she have typed, and can she undo the mistake with a command?
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.txtThe output lists three files, including file-list.txt itself. Why?
Question 16 · Find the bug
Sam wanted to create a file named report 2026.txt and typed:
echo "Quarterly results" > report 2026.txtWhat actually happened, and how should he fix the command?
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.
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?
Question 19 · Short answer
What does this command do? (Hint: see the heredoc deeper dive.)
cat << 'EOF' > team.txt
Maria
Sam
EOFQuestion 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.