0
0
Bash Scriptingscripting~5 mins

Writing to files (echo, printf) in Bash Scripting

Choose your learning style9 modes available
Introduction

Writing to files lets you save information from your script so you can use it later or share it.

Save a list of names or data generated by a script.
Create a log file to keep track of what your script did.
Store user input or results for later review.
Generate configuration files automatically.
Backup important information before making changes.
Syntax
Bash Scripting
echo "text" > filename
printf "format" > filename

echo adds a newline automatically at the end.

printf gives more control over formatting but needs explicit newlines.

Examples
This writes "Hello World" into file.txt, replacing any existing content.
Bash Scripting
echo "Hello World" > file.txt
This adds "Line 1" to the end of file.txt without removing existing content.
Bash Scripting
echo "Line 1" >> file.txt
This writes formatted text with a name and age into info.txt.
Bash Scripting
printf "Name: %s\nAge: %d\n" "Alice" 30 > info.txt
Sample Program

This script writes three lines to output.txt. It first writes a start message, then adds user info with printf, and finally adds a finish message. The cat command shows the file content.

Bash Scripting
#!/bin/bash

echo "Starting the script..." > output.txt
printf "User: %s\nScore: %d\n" "Bob" 85 >> output.txt
echo "Script finished." >> output.txt

cat output.txt
OutputSuccess
Important Notes

Use >> to add to a file without erasing it.

Remember to give your script permission to write to the file location.

Use quotes around text to avoid problems with spaces or special characters.

Summary

Use echo or printf to write text to files in bash.

echo is simple and adds a newline automatically.

printf is more flexible for formatting but needs explicit newlines.