Skip to main content
0 reactions

How to Write Text to a File in the Terminal with echo

Card titled echo and > in the Terminal, labelled shell basics, with three ticked lines: echo into hello.txt, cat hello.txt, and the text Hello from the Terminal.

echo prints a line of text. Add > and a file name, and the text goes into the file instead of onto the screen.

Every command and output on this page is real, run in Terminal with zsh 5.9 on macOS 26.

Syntax

SyntaxBash
echo "text" > file
  • echo "text": the text to write, in quotes.
  • >: send the text into a file. It creates the file if it isn’t there and replaces everything in it if it is.
  • file: the file to write.

See echo (opens in a new tab) and Redirecting Output (opens in a new tab) in the POSIX standard.

The Example

A new file named hello.txt, written twice.

Step 1: Write the Text

TerminalBash
echo "Hello from the Terminal" > hello.txt

Nothing appears on the screen: the text went into the file.

Step 2: Check the File

cat prints what’s in a file:

TerminalBash
cat hello.txt
OutputPlain text
Hello from the Terminal

Step 3: Write Again

TerminalBash
echo "A new first line" > hello.txt
TerminalBash
cat hello.txt
OutputPlain text
A new first line

The first line is gone: > replaced it.

Common Mistakes

MistakeWhat happensDo this instead
Writing with > to a file that holds text you needIts old text is gone, as Step 3 showsCheck the file with cat first, or write to a new file name

FAQ

Does the file need to exist first?

No. > creates it, as Step 1 shows.

Conclusion

echo "text" > file writes one line into a file and replaces whatever was there.

Additional Resources

macOS is a trademark of Apple Inc.

0 comments