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

Writing Files

In this page:

  1. Writing Files

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

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.