← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 5 of 13

Writing Files

Writing a file is like writing in a notebook: one arrow erases the page and starts fresh, while two arrows add new lines at the bottom.

In this page:

  1. Writing Files
Syntax
bash
echo "text" > file_name
echo "text" >> file_name
printf "format\n" arguments >> file_name

Writing Files

Writing to a file uses redirection: echo "text" > file.txt overwrites it, and >> appends. printf can be used the same way for more formatted output.

There's no dedicated "write" command in Bash — writing is always done through output redirection.

Note: Use > once at the start of a batch of writes, then switch to >> for subsequent lines, to avoid re-truncating the file each time.

Example: Writing Files

bash
#!/bin/bash
echo "First line" > notes.txt
echo "Second line" >> notes.txt
printf "Third line with %s\n" "formatting" >> notes.txt

cat notes.txt
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using > when you meant >>, which erases the file.
  2. Writing to a file in a directory that does not exist.
  3. Reading and writing the same file in one command.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.