Lesson 10: Bash File Operation (Read, Write, Copy)
Welcome to the Lesson 10: Bash File Operation (Read, Write, Copy). In this lesson, we will explore essential file operations in Bash, such as reading from, writing to, and copying files. File manipulation is a fundamental skill in Bash scripting, allowing you to automate data processing, configure system settings, or manage logs with ease. You’ll learn how to read the contents of a file, write data to it, and copy files efficiently, using simple Bash commands. Understanding these core operations will help you build powerful automation scripts, making file management tasks easier and more efficient. Let’s dive into Bash file operations and see how you can handle files like a pro!
Create Files
You can create files in Bash using the touch
command or redirection operators. The touch
command creates an empty file if it doesn’t already exist:
touch filename.txt
Alternatively, you can use the redirection operator to create a file and write to it:
echo "Hello, World!" > filename.txt
Read Files
To read the contents of a file, you can use the cat
, less
, or more
commands. The cat
command displays the entire file content:
cat filename.txt
For larger files, less
and more
allow you to scroll through the content:
less filename.txt
Write to Files
You can write to files using redirection operators. The >
operator overwrites the file, while the >>
operator appends to it:
echo "New content" > filename.txt # Overwrites the file
echo "Additional content" >> filename.txt # Appends to the file
Copy Files
To copy files, use the cp
command:
cp source.txt destination.txt
Move and Rename Files
The mv
command is used to move or rename files:
mv oldname.txt newname.txt # Renames the file
mv filename.txt /path/to/directory/ # Moves the file
Delete Files
To delete files, use the rm
command:
rm filename.txt
Checke File Existence
Before performing operations on files, it’s often useful to check if they exist. You can use conditional statements for this:
if [ -f filename.txt ]; then
echo "File exists."
else
echo "File does not exist."
fi
You can view other useful examples at the following links:
CyberWorld | Files Operation: touch, cat, less – read content of files (optimusing.dyndns.org)