# Writing to a file: echo and >

Course: Terminal Basics — https://zero2vibecode.com/learn/terminal-basics
Canonical URL: https://zero2vibecode.com/learn/terminal-basics/2-2-writing-with-echo-and-redirects

The `>` symbol sends a command's output into a file instead of onto the screen. `>` replaces the file, `>>` adds to the end.

So far commands have printed to the screen. Now send that output somewhere useful.

## The arrow

```
echo Hello from the terminal > hello.txt
```

Nothing appears on screen. That is the point: the `>` caught the output that `echo` would have printed and wrote it into `hello.txt` instead.

Check it:

```
cat hello.txt
```

```
Hello from the terminal
```

You just created a file with content in it, without ever opening an editor.

This is called **redirection**, and it is not an `echo` feature — it works with any command. `ls > files.txt` saves a folder listing. `grep ERROR log.txt > errors.txt` saves just the error lines. Anything that prints can be redirected.

<MicroQuiz
  question="You run `ls > files.txt` and see no output. What happened?"
  options="The listing went into files.txt instead of the screen | The command failed | ls does not work with redirection"
  answer="0"
  explanation="Redirection means the output goes to the file rather than the terminal. Silence is exactly what you expect."
/>

## One arrow replaces. Two arrows add.

`>` does not add to a file. It **replaces** it, completely, with no warning and no confirmation:

```
echo first > notes.txt
echo second > notes.txt
cat notes.txt
```

```
second
```

`first` is gone. There is no undo.

Use `>>` to append instead:

```
echo first > notes.txt
echo second >> notes.txt
cat notes.txt
```

```
first
second
```

This is the single most expensive typo in the terminal. `>` on a file that already matters wipes it instantly and silently. Before you point a redirect at an existing file, take the half-second to check whether you meant `>>`.

<MicroQuiz
  question="You want to add a line to a file that already has content. Which do you use?"
  options=">> — it appends to the end | > — it adds to the file | Either one works"
  answer="0"
  explanation="A single > truncates the file to nothing before writing. Only >> keeps what was there."
/>

## A useful habit

When you are not certain what a command will produce, run it *without* the redirect first and look at the output. Then run it again with the redirect.

```
grep ERROR server.log
grep ERROR server.log > errors.txt
```

Costs you one extra command, saves you writing garbage into a file you then have to clean up.

## Try it

Build a small file in two steps:

1. `echo Hello from the terminal > hello.txt` — create it with one line.
2. `echo Second line >> hello.txt` — append a second.
3. `cat hello.txt` — read both lines back.

Then try `echo Oops > hello.txt` followed by `cat hello.txt`, and watch both lines vanish. Better to learn that here than on something you care about.
