File input/output (I/O) lets scripts read data from files and save results back. This helps automate tasks that involve files, like logs or reports.
0
0
Why file I/O is core to scripting in Bash Scripting
Introduction
You want to read a list of names from a file to process each one.
You need to save the output of a script to a file for later use.
You want to append new data to an existing log file automatically.
You need to check if a file exists before running a command.
You want to extract specific information from a file and use it in your script.
Syntax
Bash Scripting
command < input_file command > output_file command >> output_file
< reads input from a file instead of the keyboard.
> writes output to a file, replacing its content.
>> appends output to the end of a file.
Examples
Reads and shows the content of
names.txt using input redirection.Bash Scripting
cat < names.txt
Writes "Hello World" into
greeting.txt, replacing any existing content.Bash Scripting
echo "Hello World" > greeting.txtAdds "New entry" at the end of
log.txt without deleting existing lines.Bash Scripting
echo "New entry" >> log.txtSample Program
This script reads each line from names.txt and prints a greeting. Then it writes a status message to status.txt.
Bash Scripting
#!/bin/bash # Read names from a file and greet each while IFS= read -r name; do echo "Hello, $name!" done < names.txt # Save a message to a file echo "Script finished successfully." > status.txt
OutputSuccess
Important Notes
Always check if the input file exists before reading to avoid errors.
Use >> to add data without deleting existing content.
File I/O lets scripts work with real data, making automation powerful.
Summary
File I/O lets scripts read and write data to files easily.
This is useful for automating tasks that involve files, like logs or reports.
Using input/output redirection is simple and powerful in bash scripting.