0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Write to File in Bash: Simple Commands and Examples

In bash, you can write to a file using the > operator to overwrite or >> to append text. For example, echo "Hello" > file.txt writes "Hello" to file.txt, replacing its content.
📐

Syntax

To write text to a file in bash, use the redirection operators:

  • command > filename: Writes output to filename, replacing existing content.
  • command >> filename: Appends output to filename, keeping existing content.

The echo command is commonly used to send text to files.

bash
echo "text" > filename

echo "more text" >> filename
💻

Example

This example shows how to write and append text to a file named greeting.txt.

bash
echo "Hello, world!" > greeting.txt
cat greeting.txt

echo "Welcome to bash scripting." >> greeting.txt
cat greeting.txt
Output
Hello, world! Hello, world! Welcome to bash scripting.
⚠️

Common Pitfalls

Common mistakes include:

  • Using > when you mean to append, which overwrites the file.
  • Forgetting to quote text with spaces, causing unexpected word splitting.
  • Not having write permission for the file or directory.
bash
echo Hello world > file.txt  # Without quotes, writes "Hello world" but can cause issues if variables or special chars are used

echo "Hello world" >> file.txt  # Correct way to append with spaces

# Wrong: overwrites file when appending was intended
# echo "New line" > file.txt

# Right: append instead
# echo "New line" >> file.txt
📊

Quick Reference

OperatorDescriptionExample
>Overwrite file with outputecho "Hi" > file.txt
>>Append output to fileecho "More" >> file.txt

Key Takeaways

Use > to overwrite a file and >> to append to it in bash.
Always quote text with spaces to avoid word splitting issues.
Check file permissions to ensure you can write to the file.
The echo command combined with redirection is the simplest way to write text to files.