BudiBadu Logo
Samplebadu

Bash by Example: Write File

Bash 5.0+

Overwriting file contents using the > output redirection operator to truncate and write new data, understanding the difference between > for overwrite and >> for append, implementing safe file writing with temporary files and atomic moves, preventing data loss through proper error handling, and using here documents for multi-line content.

Code

#!/bin/bash

file="output.txt"

# 1. Overwrite using echo
echo "This is the first line." > "$file"
echo "File created/overwritten."

# 2. Overwrite using cat (Heredoc)
cat <<EOF > "$file"
This overwrites the file again.
It supports multiple lines.
Variables like $USER are expanded.
EOF

echo "File updated via Heredoc."

# Verify content
echo -e "\n--- Content ---"
cat "$file"

rm "$file"

Explanation

Writing to files is primarily done via output redirection using the greater-than symbol >. This operator directs the standard output of a command into a file.

Crucial: Using > will overwrite the file if it exists, replacing its content entirely. If the file doesn't exist, it is created. To append instead of overwrite, use >>.

For writing multi-line blocks, Here Documents (<) are very convenient. They allow you to dump a block of text into a command (like cat), which is then redirected to the file.

Code Breakdown

6
The > operator captures the output of echo and saves it to output.txt, destroying any previous content.
10
Start of a Here Document. EOF is the delimiter token. cat reads everything until it sees EOF again.
12
Variable expansion happens inside standard Heredocs. To disable expansion, quote the delimiter: <<'EOF'.