This tutorial will teach you how to manipulate files in shell scripts. It covers the basics of file handling, including reading, writing, and deleting files.
By the end of this tutorial, you will understand how to:
Basic knowledge of shell scripting is required.
Shell scripts provide several commands for file handling, including cat
for reading, >
for writing, and rm
for deleting.
To read a file, use the cat
command followed by the file name:
cat fileName
To write to a file, use the >
operator. It will overwrite the file if it exists, or create a new file if it doesn't:
echo "Hello, World!" > fileName
To append to a file, use the >>
operator:
echo "Hello again, World!" >> fileName
To delete a file, use the rm
command:
rm fileName
# This script reads a file
fileName='test.txt'
cat $fileName
# This script writes to a file
fileName='test.txt'
echo "Hello, World!" > $fileName
# This script appends to a file
fileName='test.txt'
echo "Hello again, World!" >> $fileName
# This script deletes a file
fileName='test.txt'
rm $fileName
In this tutorial, you have learned how to read, write, and delete files in shell scripts. The next step could be learning about file permissions and how to change them.
Write a script that creates a file and writes the numbers 1 to 10 in it.
Write a script that reads the file created in Exercise 1 and displays the numbers in reverse order.
Try to handle different types of files, such as binary files or directories.