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:
Syntax
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
#!/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 try C/C++/Java/PHP code in the editor
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
- Using
>when you meant>>, which erases the file. - Writing to a file in a directory that does not exist.
- Reading and writing the same file in one command.
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: