Bash by Example: Write File
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 (<cat), which is then redirected to the file.
Code Breakdown
> operator captures the output of echo and saves it to output.txt, destroying any previous content.EOF is the delimiter token. cat reads everything until it sees EOF again.<<'EOF'.
